Object Class in Java - GeeksforGeeks
文章推薦指數: 80 %
Object class is present in java.lang package. Every class in Java is directly or indirectly derived from the Object class. If a class does ... 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 ▲RelatedArticlesAssigningvaluestostaticfinalvariablesinJavaCovariantReturnTypesinJavaObjectClassinJavaStaticclassinJavaFlexiblenatureofjava.lang.ObjectOverridingequalsmethodinJavaOverridingtoString()MethodinJavaInstanceVariableHidinginJavaStaticBlocksinJavaTheInitializerBlockinJavaInstanceInitializationBlock(IIB)inJavaStaticvsDynamicBindinginJavaWhyJavaisnotapurelyObject-OrientedLanguage?UnderstandingClassesandObjectsinJavastaticKeywordinJavafinalKeywordinJavafinal,finallyandfinalizeinJavaabstractkeywordinjavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaInterfacesinJavaAccessspecifierofmethodsininterfacesAccessmodifiersforclassesorinterfacesinJavaClassesandObjectsinJavaHowareJavaobjectsstoredinmemory?ArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaAssigningvaluestostaticfinalvariablesinJavaCovariantReturnTypesinJavaObjectClassinJavaStaticclassinJavaFlexiblenatureofjava.lang.ObjectOverridingequalsmethodinJavaOverridingtoString()MethodinJavaInstanceVariableHidinginJavaStaticBlocksinJavaTheInitializerBlockinJavaInstanceInitializationBlock(IIB)inJavaStaticvsDynamicBindinginJavaWhyJavaisnotapurelyObject-OrientedLanguage?UnderstandingClassesandObjectsinJavastaticKeywordinJavafinalKeywordinJavafinal,finallyandfinalizeinJavaabstractkeywordinjavaAbstractClassinJavaDifferencebetweenAbstractClassandInterfaceinJavaInterfacesinJavaAccessspecifierofmethodsininterfacesAccessmodifiersforclassesorinterfacesinJavaClassesandObjectsinJavaHowareJavaobjectsstoredinmemory?ArraysinJavaSplit()StringmethodinJavawithexamplesArrays.sort()inJavawithexamplesFor-eachloopinJavaReverseastringinJavaObjectClassinJavaViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: MediumLastUpdated: 03Jan,2022ReadDiscussViewDiscussion ImproveArticle SaveArticle LikeArticle Objectclassispresentinjava.langpackage.EveryclassinJavaisdirectlyorindirectlyderivedfromtheObjectclass.IfaclassdoesnotextendanyotherclassthenitisadirectchildclassofObjectandifextendsanotherclassthenitisindirectlyderived.ThereforetheObjectclassmethodsareavailabletoallJavaclasses.HenceObjectclassactsasarootofinheritancehierarchyinanyJavaProgram.UsingObjectClassMethodsTherearemethodsintheObjectclass: 1.toString():ThetoString()providesaStringrepresentationofanobjectandisusedtoconvertanobjecttoString.ThedefaulttoString()methodforclassObjectreturnsastringconsistingofthenameoftheclassofwhichtheobjectisaninstance,theat-signcharacter`@’,andtheunsignedhexadecimalrepresentationofthehashcodeoftheobject.Inotherwords,itisdefinedas://DefaultbehavioroftoString()istoprintclassname,then //@,thenunsignedhexadecimalrepresentationofthehashcode //oftheobject publicStringtoString() { returngetClass().getName()+"@"+Integer.toHexString(hashCode()); }ItisalwaysrecommendedtooverridethetoString()methodtogetourownStringrepresentationofObject.FormoreonoverrideoftoString()methodrefer–OverridingtoString()inJava Note:WheneverwetrytoprintanyObjectreference,theninternallytoString()methodiscalled.Students=newStudent(); //Belowtwostatementsareequivalent System.out.println(s); System.out.println(s.toString());2.hashCode():Foreveryobject,JVMgeneratesauniquenumberwhichishashcode.Itreturnsdistinctintegersfordistinctobjects.AcommonmisconceptionaboutthismethodisthatthehashCode()methodreturnstheaddressoftheobject,whichisnotcorrect.Itconvertstheinternaladdressoftheobjecttoanintegerbyusinganalgorithm.ThehashCode()methodisnativebecauseinJavaitisimpossibletofindtheaddressofanobject,soitusesnativelanguageslikeC/C++tofindtheaddressoftheobject.UseofhashCode()method:Itreturnsahashvaluethatisusedtosearchobjectsinacollection.JVM(JavaVirtualMachine)usesthehashcodemethodwhilesavingobjectsintohashing-relateddatastructureslikeHashSet,HashMap,Hashtable,etc.Themainadvantageofsavingobjectsbasedonhashcodeisthatsearchingbecomeseasy. Note:OverrideofhashCode()methodneedstobedonesuchthatforeveryobjectwegenerateauniquenumber.Forexample,foraStudentclass,wecanreturntherollno.ofastudentfromthehashCode()methodasitisunique. Java//Javaprogramtodemonstrateworkingof//hashCode()andtoString() publicclassStudent{ staticintlast_roll=100; introll_no; //Constructor Student() { roll_no=last_roll; last_roll++; } //OverridinghashCode() @OverridepublicinthashCode(){returnroll_no;} //Drivercode publicstaticvoidmain(Stringargs[]) { Students=newStudent(); //Belowtwostatementsareequivalent System.out.println(s); System.out.println(s.toString()); }}Output:Student@64 Student@64Notethat4*160+6*161=100 3.equals(Objectobj):Itcomparesthegivenobjectto“this”object(theobjectonwhichthemethodiscalled).Itgivesagenericwaytocompareobjectsforequality.Itisrecommendedtooverridetheequals(Objectobj)methodtogetourownequalityconditiononObjects.Formoreonoverrideofequals(Objectobj)methodrefer–OverridingequalsmethodinJavaNote:ItisgenerallynecessarytooverridethehashCode()methodwheneverthismethodisoverridden,soastomaintainthegeneralcontractforthehashCodemethod,whichstatesthatequalobjectsmusthaveequalhashcodes. 4.getClass():Itreturnstheclassobjectof“this”objectandisusedtogettheactualruntimeclassoftheobject.Itcanalsobeusedtogetmetadataofthisclass.ThereturnedClassobjectistheobjectthatislockedbystaticsynchronizedmethodsoftherepresentedclass.Asitisfinalsowedon’toverrideit.Java//JavaprogramtodemonstrateworkingofgetClass() publicclassTest{ publicstaticvoidmain(String[]args) { Objectobj=newString("GeeksForGeeks"); Classc=obj.getClass(); System.out.println("ClassofObjectobjis:" +c.getName()); }}Output: ClassofObjectobjis:java.lang.StringNote:Afterloadinga.classfile,JVMwillcreateanobjectofthetypejava.lang.ClassintheHeaparea.WecanusethisclassobjecttogetClasslevelinformation.ItiswidelyusedinReflection 5.finalize()method:Thismethodiscalledjustbeforeanobjectisgarbagecollected.ItiscalledtheGarbageCollectoronanobjectwhenthegarbagecollectordeterminesthattherearenomorereferencestotheobject.Weshouldoverridefinalize()methodtodisposeofsystemresources,performclean-upactivitiesandminimizememoryleaks.Forexample,beforedestroyingServletobjectswebcontainer,alwayscalledfinalizemethodtoperformclean-upactivitiesofthesession. Note:Thefinalizemethodiscalledjustonceonanobjecteventhoughthatobjectiseligibleforgarbagecollectionmultipletimes. Java//Javaprogramtodemonstrateworkingoffinalize() publicclassTest{ publicstaticvoidmain(String[]args) { Testt=newTest(); System.out.println(t.hashCode()); t=null; //callinggarbagecollector System.gc(); System.out.println("end"); } @Overrideprotectedvoidfinalize() { System.out.println("finalizemethodcalled"); }}Output: 366712642 finalizemethodcalled end6.clone():Itreturnsanewobjectthatisexactlythesameasthisobject.Forclone()methodreferClone().Theremainingthreemethodswait(),notify()notifyAll()arerelatedtoConcurrency.Referto Inter-threadCommunicationinJavafordetails.MyPersonalNotes arrow_drop_upSave LikePreviousCovariantReturnTypesinJavaNext StaticclassinJavaRecommendedArticlesPage:09,Nov2027,Dec1906,Apr1603,Sep1607,Jan1407,Jan1424,Dec1511,Jan1611,Jan1612,Jan1612,Jan1626,Oct1724,Mar2130,Mar1703,Apr1726,May1725,Apr1820,Sep1820,Sep1820,Sep1820,Sep1824,Sep1824,Sep1824,Sep18ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: MediumEasy Normal Medium Hard ExpertImprovedBy:JobAlertHariCharanReddy_Vadnanirshad158nishkarshgandhiArticleTags:Java-ClassandObjectJavaPracticeTags:JavaJava-ClassandObjectReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsPleaseLogintocomment...What'sNewViewDetailsViewDetailsViewDetailsImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Java - Object and Classes - Tutorialspoint
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed as wel...
- 2Object Class in Java - GeeksforGeeks
Object class is present in java.lang package. Every class in Java is directly or indirectly deriv...
- 3Classes and Objects in Java - GeeksforGeeks
A class is a user defined blueprint or prototype from which objects are created. It represents th...
- 4Java Class and Objects (With Example) - Programiz
An object is called an instance of a class. For example, suppose Bicycle is a class then Mountain...
- 5What is Class and Object in Java OOPS? Learn with Example
A Class in object oriented programming is a blueprint or prototype that defines the variables and...