Java - Object and Classes - Tutorialspoint

文章推薦指數: 80 %
投票人數:10人

Classes in Java. A class is a blueprint from which individual objects are created. Following is a sample of a class. Example. public ... Home CodingGround Jobs Whiteboard Tools Business Teachwithus JavaTutorial Java-Home Java-Overview Java-EnvironmentSetup Java-BasicSyntax Java-Object&Classes Java-Constructors Java-BasicDatatypes Java-VariableTypes Java-ModifierTypes Java-BasicOperators Java-LoopControl Java-DecisionMaking Java-Numbers Java-Characters Java-Strings Java-Arrays Java-Date&Time Java-RegularExpressions Java-Methods Java-FilesandI/O Java-Exceptions Java-Innerclasses JavaObjectOriented Java-Inheritance Java-Overriding Java-Polymorphism Java-Abstraction Java-Encapsulation Java-Interfaces Java-Packages JavaAdvanced Java-DataStructures Java-Collections Java-Generics Java-Serialization Java-Networking Java-SendingEmail Java-Multithreading Java-AppletBasics Java-Documentation JavaUsefulResources Java-QuestionsandAnswers Java-QuickGuide Java-UsefulResources Java-Discussion Java-Examples SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho Java-ObjectandClasses Advertisements PreviousPage NextPage  CompleteJavaProgrammingFundamentalsWithSampleProjects 98Lectures 7.5hours EmenwaGlobal,EjikeIfeanyiChukwu MoreDetail GetyourJavadreamjob!Beginnersinterviewpreparation 85Lectures 6hours YuvalIshay MoreDetail CoreJavabootcampprogramwithHandsonpractice Featured 99Lectures 17hours PrashantMishra MoreDetail JavaisanObject-OrientedLanguage.AsalanguagethathastheObject-Orientedfeature,Javasupportsthefollowingfundamentalconcepts− Polymorphism Inheritance Encapsulation Abstraction Classes Objects Instance Method MessagePassing Inthischapter,wewilllookintotheconcepts-ClassesandObjects. Object−Objectshavestatesandbehaviors.Example:Adoghasstates-color,name,breedaswellasbehaviors–waggingthetail,barking,eating.Anobjectisaninstanceofaclass. Class−Aclasscanbedefinedasatemplate/blueprintthatdescribesthebehavior/statethattheobjectofitstypesupport. ObjectsinJava Letusnowlookdeepintowhatareobjects.Ifweconsiderthereal-world,wecanfindmanyobjectsaroundus,cars,dogs,humans,etc.Alltheseobjectshaveastateandabehavior. Ifweconsideradog,thenitsstateis-name,breed,color,andthebehavioris-barking,waggingthetail,running. Ifyoucomparethesoftwareobjectwithareal-worldobject,theyhaveverysimilarcharacteristics. Softwareobjectsalsohaveastateandabehavior.Asoftwareobject'sstateisstoredinfieldsandbehaviorisshownviamethods. Soinsoftwaredevelopment,methodsoperateontheinternalstateofanobjectandtheobject-to-objectcommunicationisdoneviamethods. ClassesinJava Aclassisablueprintfromwhichindividualobjectsarecreated. Followingisasampleofaclass. Example publicclassDog{ Stringbreed; intage; Stringcolor; voidbarking(){ } voidhungry(){ } voidsleeping(){ } } Aclasscancontainanyofthefollowingvariabletypes. Localvariables−Variablesdefinedinsidemethods,constructorsorblocksarecalledlocalvariables.Thevariablewillbedeclaredandinitializedwithinthemethodandthevariablewillbedestroyedwhenthemethodhascompleted. Instancevariables−Instancevariablesarevariableswithinaclassbutoutsideanymethod.Thesevariablesareinitializedwhentheclassisinstantiated.Instancevariablescanbeaccessedfrominsideanymethod,constructororblocksofthatparticularclass. Classvariables−Classvariablesarevariablesdeclaredwithinaclass,outsideanymethod,withthestatickeyword. Aclasscanhaveanynumberofmethodstoaccessthevalueofvariouskindsofmethods.Intheaboveexample,barking(),hungry()andsleeping()aremethods. FollowingaresomeoftheimportanttopicsthatneedtobediscussedwhenlookingintoclassesoftheJavaLanguage. Constructors Whendiscussingaboutclasses,oneofthemostimportantsubtopicwouldbeconstructors.Everyclasshasaconstructor.Ifwedonotexplicitlywriteaconstructorforaclass,theJavacompilerbuildsadefaultconstructorforthatclass. Eachtimeanewobjectiscreated,atleastoneconstructorwillbeinvoked.Themainruleofconstructorsisthattheyshouldhavethesamenameastheclass.Aclasscanhavemorethanoneconstructor. Followingisanexampleofaconstructor− Example publicclassPuppy{ publicPuppy(){ } publicPuppy(Stringname){ //Thisconstructorhasoneparameter,name. } } JavaalsosupportsSingletonClasseswhereyouwouldbeabletocreateonlyoneinstanceofaclass. Note−Wehavetwodifferenttypesofconstructors.Wearegoingtodiscussconstructorsindetailinthesubsequentchapters. CreatinganObject Asmentionedpreviously,aclassprovidestheblueprintsforobjects.Sobasically,anobjectiscreatedfromaclass.InJava,thenewkeywordisusedtocreatenewobjects. Therearethreestepswhencreatinganobjectfromaclass− Declaration−Avariabledeclarationwithavariablenamewithanobjecttype. Instantiation−The'new'keywordisusedtocreatetheobject. Initialization−The'new'keywordisfollowedbyacalltoaconstructor.Thiscallinitializesthenewobject. Followingisanexampleofcreatinganobject− Example LiveDemo publicclassPuppy{ publicPuppy(Stringname){ //Thisconstructorhasoneparameter,name. System.out.println("PassedNameis:"+name); } publicstaticvoidmain(String[]args){ //FollowingstatementwouldcreateanobjectmyPuppy PuppymyPuppy=newPuppy("tommy"); } } Ifwecompileandruntheaboveprogram,thenitwillproducethefollowingresult− Output PassedNameis:tommy AccessingInstanceVariablesandMethods Instancevariablesandmethodsareaccessedviacreatedobjects.Toaccessaninstancevariable,followingisthefullyqualifiedpath− /*Firstcreateanobject*/ ObjectReference=newConstructor(); /*Nowcallavariableasfollows*/ ObjectReference.variableName; /*Nowyoucancallaclassmethodasfollows*/ ObjectReference.MethodName(); Example Thisexampleexplainshowtoaccessinstancevariablesandmethodsofaclass. LiveDemo publicclassPuppy{ intpuppyAge; publicPuppy(Stringname){ //Thisconstructorhasoneparameter,name. System.out.println("Namechosenis:"+name); } publicvoidsetAge(intage){ puppyAge=age; } publicintgetAge(){ System.out.println("Puppy'sageis:"+puppyAge); returnpuppyAge; } publicstaticvoidmain(String[]args){ /*Objectcreation*/ PuppymyPuppy=newPuppy("tommy"); /*Callclassmethodtosetpuppy'sage*/ myPuppy.setAge(2); /*Callanotherclassmethodtogetpuppy'sage*/ myPuppy.getAge(); /*Youcanaccessinstancevariableasfollowsaswell*/ System.out.println("VariableValue:"+myPuppy.puppyAge); } } Ifwecompileandruntheaboveprogram,thenitwillproducethefollowingresult− Output Namechosenis:tommy Puppy'sageis:2 VariableValue:2 SourceFileDeclarationRules Asthelastpartofthissection,let'snowlookintothesourcefiledeclarationrules.Theserulesareessentialwhendeclaringclasses,importstatementsandpackagestatementsinasourcefile. Therecanbeonlyonepublicclasspersourcefile. Asourcefilecanhavemultiplenon-publicclasses. Thepublicclassnameshouldbethenameofthesourcefileaswellwhichshouldbeappendedby.javaattheend.Forexample:theclassnameispublicclassEmployee{}thenthesourcefileshouldbeasEmployee.java. Iftheclassisdefinedinsideapackage,thenthepackagestatementshouldbethefirststatementinthesourcefile. Ifimportstatementsarepresent,thentheymustbewrittenbetweenthepackagestatementandtheclassdeclaration.Iftherearenopackagestatements,thentheimportstatementshouldbethefirstlineinthesourcefile. Importandpackagestatementswillimplytoalltheclassespresentinthesourcefile.Itisnotpossibletodeclaredifferentimportand/orpackagestatementstodifferentclassesinthesourcefile. Classeshaveseveralaccesslevelsandtherearedifferenttypesofclasses;abstractclasses,finalclasses,etc.Wewillbeexplainingaboutalltheseintheaccessmodifierschapter. Apartfromtheabovementionedtypesofclasses,JavaalsohassomespecialclassescalledInnerclassesandAnonymousclasses. JavaPackage Insimplewords,itisawayofcategorizingtheclassesandinterfaces.WhendevelopingapplicationsinJava,hundredsofclassesandinterfaceswillbewritten,thereforecategorizingtheseclassesisamustaswellasmakeslifemucheasier. ImportStatements InJavaifafullyqualifiedname,whichincludesthepackageandtheclassnameisgiven,thenthecompilercaneasilylocatethesourcecodeorclasses.Importstatementisawayofgivingtheproperlocationforthecompilertofindthatparticularclass. Forexample,thefollowinglinewouldaskthecompilertoloadalltheclassesavailableindirectoryjava_installation/java/io− importjava.io.*; ASimpleCaseStudy Forourcasestudy,wewillbecreatingtwoclasses.TheyareEmployeeandEmployeeTest. Firstopennotepadandaddthefollowingcode.RememberthisistheEmployeeclassandtheclassisapublicclass.Now,savethissourcefilewiththenameEmployee.java. TheEmployeeclasshasfourinstancevariables-name,age,designationandsalary.Theclasshasoneexplicitlydefinedconstructor,whichtakesaparameter. Example importjava.io.*; publicclassEmployee{ Stringname; intage; Stringdesignation; doublesalary; //ThisistheconstructoroftheclassEmployee publicEmployee(Stringname){ this.name=name; } //AssigntheageoftheEmployeetothevariableage. publicvoidempAge(intempAge){ age=empAge; } /*Assignthedesignationtothevariabledesignation.*/ publicvoidempDesignation(StringempDesig){ designation=empDesig; } /*Assignthesalarytothevariable salary.*/ publicvoidempSalary(doubleempSalary){ salary=empSalary; } /*PrinttheEmployeedetails*/ publicvoidprintEmployee(){ System.out.println("Name:"+name); System.out.println("Age:"+age); System.out.println("Designation:"+designation); System.out.println("Salary:"+salary); } } Asmentionedpreviouslyinthistutorial,processingstartsfromthemainmethod.Therefore,inorderforustorunthisEmployeeclassthereshouldbeamainmethodandobjectsshouldbecreated.Wewillbecreatingaseparateclassforthesetasks. FollowingistheEmployeeTestclass,whichcreatestwoinstancesoftheclassEmployeeandinvokesthemethodsforeachobjecttoassignvaluesforeachvariable. SavethefollowingcodeinEmployeeTest.javafile. importjava.io.*; publicclassEmployeeTest{ publicstaticvoidmain(Stringargs[]){ /*Createtwoobjectsusingconstructor*/ EmployeeempOne=newEmployee("JamesSmith"); EmployeeempTwo=newEmployee("MaryAnne"); //Invokingmethodsforeachobjectcreated empOne.empAge(26); empOne.empDesignation("SeniorSoftwareEngineer"); empOne.empSalary(1000); empOne.printEmployee(); empTwo.empAge(21); empTwo.empDesignation("SoftwareEngineer"); empTwo.empSalary(500); empTwo.printEmployee(); } } Now,compileboththeclassesandthenrunEmployeeTesttoseetheresultasfollows− Output C:\>javacEmployee.java C:\>javacEmployeeTest.java C:\>javaEmployeeTest Name:JamesSmith Age:26 Designation:SeniorSoftwareEngineer Salary:1000.0 Name:MaryAnne Age:21 Designation:SoftwareEngineer Salary:500.0 WhatisNext? Inthenextsession,wewilldiscussthebasicdatatypesinJavaandhowtheycanbeusedwhendevelopingJavaapplications. PreviousPage PrintPage NextPage  Advertisements



請為這篇文章評分?