Classes and Objects in Java - GeeksforGeeks

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

A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#HTMLJavaScriptPHPSQLScalaPerlGoLanguageKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebDevelopmentHTMLCSSJavaScriptPHPCSSFrameworksBootstrapTailwindCSSFoundationCSSMaterializeCSSBulmaPureCSSPrimerCSSBlazeUISemanticUIJavaScriptFrameworksAngularJSNodeJSJavaScriptLibrariesjQueryReactJSSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialGFGSheetsWebDevCheatSheetsHTMLCheatSheetCSSCheatSheetJSCheatSheetjQueryCheatSheetCompany-WiseSDESheetsFacebookSDESheetAmazonSDESheetAppleSDESheetNetflixSDESheetGoogleSDESheetWiproCodingSheetInfosysCodingSheetTCSCodingSheetCognizantCodingSheetHCLCodingSheetDSASheetsSDESheetFAANGCodingSheetLoveBabbarSheetMassRecruiterSheetProduct-BasedCodingSheetCompany-WisePreparationSheetArraySheetStringSheetTreeSheetGraphSheetDPSheetSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblemsContests ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningJavaScriptSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesBasicsofJavaJavaTutorialIntroductiontoJavaSimilaritiesandDifferencebetweenJavaandC++SettinguptheenvironmentinJavaJavaBasicSyntaxJavaHelloWorldProgramDifferencesbetweenJDK,JREandJVMHowJVMWorks–JVMArchitecture?JavaIdentifiersVariables&DataTypesinJavaVariablesinJavaScopeofVariablesInJavaDatatypesinJavaOperatorsinJavaOperatorsinJavaJavaArithmeticOperatorswithExamplesJavaAssignmentOperatorswithExamplesJavaUnaryOperatorwithExamplesJavaRelationalOperatorswithExamplesJavaLogicalOperatorswithExamplesJavaTernaryOperatorwithExamplesBitwiseOperatorsinJavaPackagesinJavaPackagesInJavaFlowControlinJavaDecisionMakinginJava(if,if-else,switch,break,continue,jump)JavaifstatementwithExamplesJavaif-elsestatementwithExamplesJavaif-else-ifladderwithExamplesLoopsinJavaLoopsinJavaJavaForloopwithExamplesJavawhileloopwithExamplesJavado-whileloopwithExamplesFor-eachloopinJavaJumpStatementsinJavaContinueStatementinJavaBreakstatementinJavareturnkeywordinJavaArraysinJavaArraysinJavaMultidimensionalArraysinJavaJaggedArrayinJavaStringsinJavaStringsinJavaStringclassinJava|Set1StringBufferclassinJavaStringBuilderClassinJavawithExamplesOOPSinJavaObjectOrientedProgramming(OOPs)ConceptinJavaClassesandObjectsinJavaMethodsinJavaAccessModifiersinJavaWrapperClassesinJavaNeedofWrapperClassesinJavaConstructorsinJavaConstructorsinJavaCopyConstructorinJavaConstructorChainingInJavawithExamplesPrivateConstructorsandSingletonClassesinJavaInheritance&PolymorphisminJavaInheritanceinJavaJavaandMultipleInheritanceComparisonofInheritanceinC++andJavaPolymorphisminJavaDynamicMethodDispatchorRuntimePolymorphisminJavaMethodoverloading&OveridingMethodOverloadinginJavaDifferentwaysofMethodOverloadinginJavaOverridinginJavaDifferenceBetweenMethodOverloadingandMethodOverridinginJavaAbstraction&EncapsulationAbstractioninJavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaEncapsulationinJavaInterfacesinJavaInterfacesinJavaNestedInterfaceinJavaMarkerinterfaceinJavaFunctionalInterfacesinJavaComparatorInterfaceinJavawithExamplesKeywordsinJavaListofallJavaKeywordsSuperKeywordinJavafinalKeywordinJavaabstractkeywordinjavastaticKeywordinJava‘this’referenceinJavaenuminJavaExceptionHandlinginJavaExceptionsinJavaTypesofExceptioninJavawithExamplesCheckedvsUncheckedExceptionsinJavaTry,catch,throwandthrowsinJavaFlowcontrolintrycatchfinallyinJavathrowandthrowsinJavaUser-definedCustomExceptioninJavaCollectionFrameworkCollectionsinJavaCollectionsClassinJavaListInterfaceinJavawithExamplesArrayListinJavaVectorClassinJavaStackClassinJavaLinkedListinJavaQueueInterfaceInJavaPriorityQueueinJavaDequeinterfaceinJavawithExampleArrayDequeinJavaSetinJavaHashSetinJavaLinkedHashSetinJavawithExamplesSortedSetInterfaceinJavawithExamplesNavigableSetinJavawithExamplesTreeSetinJavaMapInterfaceinJavaHashMapinJavawithExamplesHashtableinJavaLinkedHashMapinJavaSortedMapInterfaceinJavawithExamplesTreeMapinJavaMulti-threadinginJavaMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaThreadPriorityinMultithreadingThreadPoolsinJavaSynchronizationinJavaMethodandBlockSynchronizationinJavaImportanceofThreadSynchronizationinJavaThreadSafetyandhowtoachieveitinJavaBasicsofJavaJavaTutorialIntroductiontoJavaSimilaritiesandDifferencebetweenJavaandC++SettinguptheenvironmentinJavaJavaBasicSyntaxJavaHelloWorldProgramDifferencesbetweenJDK,JREandJVMHowJVMWorks–JVMArchitecture?JavaIdentifiersVariables&DataTypesinJavaVariablesinJavaScopeofVariablesInJavaDatatypesinJavaOperatorsinJavaOperatorsinJavaJavaArithmeticOperatorswithExamplesJavaAssignmentOperatorswithExamplesJavaUnaryOperatorwithExamplesJavaRelationalOperatorswithExamplesJavaLogicalOperatorswithExamplesJavaTernaryOperatorwithExamplesBitwiseOperatorsinJavaPackagesinJavaPackagesInJavaFlowControlinJavaDecisionMakinginJava(if,if-else,switch,break,continue,jump)JavaifstatementwithExamplesJavaif-elsestatementwithExamplesJavaif-else-ifladderwithExamplesLoopsinJavaLoopsinJavaJavaForloopwithExamplesJavawhileloopwithExamplesJavado-whileloopwithExamplesFor-eachloopinJavaJumpStatementsinJavaContinueStatementinJavaBreakstatementinJavareturnkeywordinJavaArraysinJavaArraysinJavaMultidimensionalArraysinJavaJaggedArrayinJavaStringsinJavaStringsinJavaStringclassinJava|Set1StringBufferclassinJavaStringBuilderClassinJavawithExamplesOOPSinJavaObjectOrientedProgramming(OOPs)ConceptinJavaClassesandObjectsinJavaMethodsinJavaAccessModifiersinJavaWrapperClassesinJavaNeedofWrapperClassesinJavaConstructorsinJavaConstructorsinJavaCopyConstructorinJavaConstructorChainingInJavawithExamplesPrivateConstructorsandSingletonClassesinJavaInheritance&PolymorphisminJavaInheritanceinJavaJavaandMultipleInheritanceComparisonofInheritanceinC++andJavaPolymorphisminJavaDynamicMethodDispatchorRuntimePolymorphisminJavaMethodoverloading&OveridingMethodOverloadinginJavaDifferentwaysofMethodOverloadinginJavaOverridinginJavaDifferenceBetweenMethodOverloadingandMethodOverridinginJavaAbstraction&EncapsulationAbstractioninJavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaEncapsulationinJavaInterfacesinJavaInterfacesinJavaNestedInterfaceinJavaMarkerinterfaceinJavaFunctionalInterfacesinJavaComparatorInterfaceinJavawithExamplesKeywordsinJavaListofallJavaKeywordsSuperKeywordinJavafinalKeywordinJavaabstractkeywordinjavastaticKeywordinJava‘this’referenceinJavaenuminJavaExceptionHandlinginJavaExceptionsinJavaTypesofExceptioninJavawithExamplesCheckedvsUncheckedExceptionsinJavaTry,catch,throwandthrowsinJavaFlowcontrolintrycatchfinallyinJavathrowandthrowsinJavaUser-definedCustomExceptioninJavaCollectionFrameworkCollectionsinJavaCollectionsClassinJavaListInterfaceinJavawithExamplesArrayListinJavaVectorClassinJavaStackClassinJavaLinkedListinJavaQueueInterfaceInJavaPriorityQueueinJavaDequeinterfaceinJavawithExampleArrayDequeinJavaSetinJavaHashSetinJavaLinkedHashSetinJavawithExamplesSortedSetInterfaceinJavawithExamplesNavigableSetinJavawithExamplesTreeSetinJavaMapInterfaceinJavaHashMapinJavawithExamplesHashtableinJavaLinkedHashMapinJavaSortedMapInterfaceinJavawithExamplesTreeMapinJavaMulti-threadinginJavaMultithreadinginJavaLifecycleandStatesofaThreadinJavaMainthreadinJavaJavaThreadPriorityinMultithreadingThreadPoolsinJavaSynchronizationinJavaMethodandBlockSynchronizationinJavaImportanceofThreadSynchronizationinJavaThreadSafetyandhowtoachieveitinJavaClassesandObjectsinJavaViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 04Sep,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle   ClassesandObjectsarebasicconceptsofObjectOrientedProgrammingthatrevolvearoundreallifeentities.Class1.Classisasetofobjectwhichsharescommoncharacteristics/behaviorandcommonproperties/attributes.2.Classisnotarealworldentity.Itisjustatemplateorblueprintorprototypefromwhichobjectsarecreated.3.Classdoesnotoccupymemory.4.Classisagroupofvariablesofdifferentdatatypesandgroupofmethods.Aclassinjavacancontain:•datamember•method•constructor•nestedclassand •interfaceSyntaxtodeclareaclass: access_modifierclass { datamember; method; constructor; nestedclass; interface; }Eg: •Animal•Student•Bird•Vehicle•Company JavaclassStudent{     intid;//datamember(alsoinstancevariable)     Stringname;//datamember(alsoinstancevariable)      publicstaticvoidmain(Stringargs[])    {         Students1=newStudent();//creatinganobjectofStudent         System.out.println(s1.id);         System.out.println(s1.name);      } } Output0 nullAclassisauserdefinedblueprintorprototypefromwhichobjectsarecreated.Itrepresentsthesetofpropertiesormethodsthatarecommontoallobjectsofonetype.Ingeneral,classdeclarationscanincludethesecomponents,inorder: Modifiers:Aclasscanbepublicorhasdefaultaccess(Referthisfordetails).Classkeyword:classkeywordisusedtocreateaclass.Classname: Thenameshouldbeginwithaninitialletter(capitalizedbyconvention).Superclass(ifany):Thenameoftheclass’sparent(superclass),ifany,precededbythekeywordextends.Aclasscanonlyextend(subclass)oneparent.Interfaces(ifany):Acomma-separatedlistofinterfacesimplementedbytheclass,ifany,precededbythekeywordimplements.Aclasscanimplementmorethanoneinterface.Body:Theclassbody issurroundedbybraces,{}.Constructorsareusedforinitializingnewobjects.Fieldsarevariablesthatprovidethestateoftheclassanditsobjects,andmethodsareusedtoimplementthebehavioroftheclassanditsobjects.Therearevarioustypesofclassesthatareusedinrealtimeapplicationssuchas nestedclasses,anonymousclasses,lambdaexpressions. ObjectItisabasicunitofObject-OrientedProgramming andrepresentsreallifeentities.AtypicalJavaprogramcreatesmanyobjects,whichasyouknow,interactbyinvokingmethods.Anobjectconsistsof: State:Itisrepresentedbyattributesofanobject.Italsoreflectsthepropertiesofanobject.Behavior:Itisrepresentedbymethodsofanobject.Italsoreflectstheresponseofanobjectwithotherobjects.Identity:Itgivesauniquenametoanobjectandenablesoneobjecttointeractwithotherobjects.Exampleofanobject:dogObjectscorrespondtothingsfoundintherealworld.Forexample,agraphicsprogrammayhaveobjectssuchas“circle”,“square”,and“menu”.Anonlineshoppingsystemmighthaveobjectssuchas“shoppingcart”,“customer”,and“product”.  DeclaringObjects(Alsocalledinstantiatingaclass)Whenanobjectofaclassiscreated,theclassissaidtobeinstantiated.Alltheinstancessharetheattributesandthebehavioroftheclass.Butthevaluesofthoseattributes,i.e.thestateareuniqueforeachobject.Asingleclassmayhaveanynumberofinstances.Example: Aswedeclarevariableslike(typename;).Thisnotifiesthecompilerthatwewillusethenametorefertodatawhosetypeistype.Withaprimitivevariable,thisdeclarationalsoreservestheproperamountofmemoryforthevariable.Soforreferencevariable, thetypemustbestrictlyaconcreteclassname.Ingeneral,wecan’tcreateobjectsofanabstractclassoraninterface.  Dogtuffy;Ifwedeclareareferencevariable(tuffy)likethis,itsvaluewillbeundetermined(null)untilanobjectisactuallycreatedandassignedtoit.Simplydeclaringareferencevariabledoesnotcreateanobject. InitializinganobjectThenewoperatorinstantiatesaclassbyallocatingmemoryforanewobjectandreturningareferencetothatmemory.Thenewoperatoralsoinvokestheclass constructor. Java//ClassDeclaration publicclassDog{    //InstanceVariables    Stringname;    Stringbreed;    intage;    Stringcolor;     //ConstructorDeclarationofClass    publicDog(Stringname,Stringbreed,                   intage,Stringcolor)    {        this.name=name;        this.breed=breed;        this.age=age;        this.color=color;    }     //method1    publicStringgetName()    {        returnname;    }     //method2    publicStringgetBreed()    {        returnbreed;    }     //method3    publicintgetAge()    {        returnage;    }     //method4    publicStringgetColor()    {        returncolor;    }     @Override    publicStringtoString()    {        return("Himynameis"+this.getName()+               ".\nMybreed,ageandcolorare"+               this.getBreed()+","+this.getAge()+               ","+this.getColor());    }     publicstaticvoidmain(String[]args)    {        Dogtuffy=newDog("tuffy","papillon",5,"white");        System.out.println(tuffy.toString());    }}Output: Himynameistuffy. Mybreed,ageandcolorarepapillon,5,whiteThisclasscontainsasingleconstructor.Wecanrecognizeaconstructorbecauseitsdeclarationusesthesamenameastheclassandithasnoreturntype.TheJavacompilerdifferentiatestheconstructorsbasedonthenumberandthetypeofthearguments.TheconstructorintheDogclasstakesfourarguments.Thefollowingstatementprovides“tuffy”,”papillon”,5,”white”asvaluesforthosearguments:Dogtuffy=newDog("tuffy","papillon",5,"white");Theresultofexecutingthisstatementcanbeillustratedas:Note:Allclasseshaveatleastoneconstructor.Ifaclassdoesnotexplicitlydeclareany,theJavacompilerautomaticallyprovidesano-argumentconstructor,alsocalledthedefaultconstructor.Thisdefaultconstructorcallstheclassparent’sno-argumentconstructor(asitcontainsonlyonestatementi.esuper();),ortheObjectclassconstructoriftheclasshasnootherparent(astheObjectclassistheparentofallclasseseitherdirectlyorindirectly). WaystocreateanobjectofaclassTherearefourwaystocreateobjectsinjava.Strictlyspeakingthereisonlyoneway(byusingnewkeyword),andtherestinternallyusenewkeyword. Usingnewkeyword:Itisthemostcommonandgeneralwaytocreateanobjectinjava.Example://creatingobjectofclassTest Testt=newTest();UsingClass.forName(StringclassName)method:Thereisapre-definedclassinjava.langpackagewithnameClass.TheforName(StringclassName)methodreturnstheClassobjectassociatedwiththeclasswiththegivenstringname.Wehavetogiveafullyqualifiednameforaclass.OncallingnewInstance()methodonthisClassobjectreturnsnewinstanceoftheclasswiththegivenstringname.//creatingobjectofpublicclassTest //considerclassTestpresentincom.p1package Testobj=(Test)Class.forName("com.p1.Test").newInstance();Usingclone()method:clone()methodispresentinObjectclass.Itcreatesandreturnsacopyoftheobject. //creatingobjectofclassTest Testt1=newTest(); //creatingcloneofaboveobject Testt2=(Test)t1.clone();Deserialization:De-serializationisatechniqueofreadinganobjectfromthesavedstateinafile.ReferSerialization/De-Serializationinjava FileInputStreamfile=newFileInputStream(filename); ObjectInputStreamin=newObjectInputStream(file); Objectobj=in.readObject();Creatingmultipleobjectsbyonetypeonly(Agoodpractice) Inreal-time,weneeddifferentobjectsofaclassindifferentmethods.Creatinganumberofreferencesforstoringthemisnotagoodpractice andthereforewedeclareastaticreferencevariableanduseitwheneverrequired.Inthiscase,thewastageofmemoryisless.TheobjectsthatarenotreferencedanymorewillbedestroyedbyGarbageCollectorofjava.Example: Testtest=newTest(); test=newTest();Ininheritancesystem,weuseparentclassreferencevariabletostoreasub-classobject.Inthiscase,wecanswitchintodifferentsubclassobjectsusingsamereferencedvariable.Example:classAnimal{} classDogextendsAnimal{} classCatextendsAnimal{} publicclassTest { //usingDogobject Animalobj=newDog(); //usingCatobject obj=newCat(); }AnonymousobjectsAnonymousobjectsareobjectsthatareinstantiatedbutarenotstoredinareferencevariable.  Theyareusedforimmediatemethodcalling.Theywillbedestroyedaftermethodcalling.Theyarewidelyusedindifferentlibraries.Forexample, inAWTlibraries,theyareusedtoperformsomeactiononcapturinganevent(egakeypress).Intheexamplebelow,whenakeyisbutton(referredbythebtn)ispressed,wearesimplycreatinganonymousobjectofEventHandlerclassforjustcallinghandlemethod.btn.setOnAction(newEventHandler() { publicvoidhandle(ActionEventevent) { System.out.println("HelloWorld!"); } });ThisarticleiscontributedbyGauravMiglani.IfyoulikeGeeksforGeeksandwouldliketocontribute,youcanalsowriteanarticleusingwrite.geeksforgeeks.orgormailyourarticletoreview-team@geeksforgeeks.org.SeeyourarticleappearingontheGeeksforGeeksmainpageandhelpotherGeeks.Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopicdiscussedabove. MyPersonalNotes arrow_drop_upSave LikePreviousObjectOrientedProgramming(OOPs)ConceptinJavaNext MethodsinJavaRecommendedArticlesPage:11,Sep1820,May1713,Nov1701,Dec1022,Mar1718,Feb1815,Jul2220,Feb1616,Jul1608,Mar2108,Mar2125,Sep1430,Jan1606,Jun1803,Oct1809,Nov1810,Dec2016,Nov2006,Dec2016,Dec2002,Jan2120,Dec2002,Jan2116,Dec20ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertImprovedBy:MamunRezachandan1701aadarshbaidritikjangir06aditiyadav20102001ArticleTags:java-basicsJavaSchoolProgrammingPracticeTags:JavaReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?