Object (Java Platform SE 7 ) - Oracle Help Center

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

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. Overview Package Class Use Tree Deprecated Index Help Java™ PlatformStandard Ed. 7 PrevClass NextClass Frames NoFrames AllClasses Summary:  Nested |  Field |  Constr |  Method Detail:  Field |  Constr |  Method java.lang.Object publicclassObject ClassObjectistherootoftheclasshierarchy. EveryclasshasObjectasasuperclass.Allobjects, includingarrays,implementthemethodsofthisclass. Since: JDK1.0 SeeAlso:Class ConstructorSummary Constructors  ConstructorandDescription Object()  MethodSummary Methods  ModifierandType MethodandDescription protectedObject clone() Createsandreturnsacopyofthisobject. boolean equals(Object obj) Indicateswhethersomeotherobjectis"equalto"thisone. protectedvoid finalize() Calledbythegarbagecollectoronanobjectwhengarbagecollection determinesthattherearenomorereferencestotheobject. Class> getClass() ReturnstheruntimeclassofthisObject. int hashCode() Returnsahashcodevaluefortheobject. void notify() Wakesupasinglethreadthatiswaitingonthisobject's monitor. void notifyAll() Wakesupallthreadsthatarewaitingonthisobject'smonitor. String toString() Returnsastringrepresentationoftheobject. void wait() Causesthecurrentthreadtowaituntilanotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject. void wait(long timeout) Causesthecurrentthreadtowaituntileitheranotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject,ora specifiedamountoftimehaselapsed. void wait(long timeout, int nanos) Causesthecurrentthreadtowaituntilanotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject,or someotherthreadinterruptsthecurrentthread,oracertain amountofrealtimehaselapsed. ConstructorDetail Object public Object() MethodDetail getClass publicfinal Class> getClass() ReturnstheruntimeclassofthisObject.Thereturned Classobjectistheobjectthatislockedbystaticsynchronizedmethodsoftherepresentedclass. TheactualresulttypeisClass where|X|istheerasureofthestatictypeofthe expressiononwhichgetClassiscalled.For example,nocastisrequiredinthiscodefragment: Numbern=0; Classc=n.getClass(); Returns:TheClassobjectthatrepresentstheruntime classofthisobject.SeeAlso:Literals,section15.8.2of TheJava™LanguageSpecification. hashCode public int hashCode() Returnsahashcodevaluefortheobject.Thismethodis supportedforthebenefitofhashtablessuchasthoseprovidedby HashMap. ThegeneralcontractofhashCodeis: Wheneveritisinvokedonthesameobjectmorethanonceduring anexecutionofaJavaapplication,thehashCodemethod mustconsistentlyreturnthesameinteger,providednoinformation usedinequalscomparisonsontheobjectismodified. Thisintegerneednotremainconsistentfromoneexecutionofan applicationtoanotherexecutionofthesameapplication. Iftwoobjectsareequalaccordingtotheequals(Object) method,thencallingthehashCodemethodoneachof thetwoobjectsmustproducethesameintegerresult. Itisnotrequiredthatiftwoobjectsareunequal accordingtotheequals(java.lang.Object) method,thencallingthehashCodemethodoneachofthe twoobjectsmustproducedistinctintegerresults.However,the programmershouldbeawarethatproducingdistinctintegerresults forunequalobjectsmayimprovetheperformanceofhashtables. Asmuchasisreasonablypractical,thehashCodemethoddefinedby classObjectdoesreturndistinctintegersfordistinct objects.(Thisistypicallyimplementedbyconvertingtheinternal addressoftheobjectintoaninteger,butthisimplementation techniqueisnotrequiredbythe JavaTMprogramminglanguage.) Returns:ahashcodevalueforthisobject.SeeAlso:equals(java.lang.Object), System.identityHashCode(java.lang.Object) equals public boolean equals(Object obj) Indicateswhethersomeotherobjectis"equalto"thisone. Theequalsmethodimplementsanequivalencerelation onnon-nullobjectreferences: Itisreflexive:foranynon-nullreferencevalue x,x.equals(x)shouldreturn true. Itissymmetric:foranynon-nullreferencevalues xandy,x.equals(y) shouldreturntrueifandonlyif y.equals(x)returnstrue. Itistransitive:foranynon-nullreferencevalues x,y,andz,if x.equals(y)returnstrueand y.equals(z)returnstrue,then x.equals(z)shouldreturntrue. Itisconsistent:foranynon-nullreferencevalues xandy,multipleinvocationsof x.equals(y)consistentlyreturntrue orconsistentlyreturnfalse,providedno informationusedinequalscomparisonsonthe objectsismodified. Foranynon-nullreferencevaluex, x.equals(null)shouldreturnfalse. TheequalsmethodforclassObjectimplements themostdiscriminatingpossibleequivalencerelationonobjects; thatis,foranynon-nullreferencevaluesxand y,thismethodreturnstrueifandonly ifxandyrefertothesameobject (x==yhasthevaluetrue). NotethatitisgenerallynecessarytooverridethehashCode methodwheneverthismethodisoverridden,soastomaintainthe generalcontractforthehashCodemethod,whichstates thatequalobjectsmusthaveequalhashcodes. Parameters:obj-thereferenceobjectwithwhichtocompare. Returns:trueifthisobjectisthesameastheobj argument;falseotherwise.SeeAlso:hashCode(), HashMap clone protected Object clone() throwsCloneNotSupportedException Createsandreturnsacopyofthisobject.Theprecisemeaning of"copy"maydependontheclassoftheobject.Thegeneral intentisthat,foranyobjectx,theexpression: x.clone()!=x willbetrue,andthattheexpression: x.clone().getClass()==x.getClass() willbetrue,butthesearenotabsoluterequirements. Whileitistypicallythecasethat: x.clone().equals(x) willbetrue,thisisnotanabsoluterequirement. Byconvention,thereturnedobjectshouldbeobtainedbycalling super.clone.Ifaclassandallofitssuperclasses(except Object)obeythisconvention,itwillbethecasethat x.clone().getClass()==x.getClass(). Byconvention,theobjectreturnedbythismethodshouldbeindependent ofthisobject(whichisbeingcloned).Toachievethisindependence, itmaybenecessarytomodifyoneormorefieldsoftheobjectreturned bysuper.clonebeforereturningit.Typically,thismeans copyinganymutableobjectsthatcomprisetheinternal"deepstructure" oftheobjectbeingclonedandreplacingthereferencestothese objectswithreferencestothecopies.Ifaclasscontainsonly primitivefieldsorreferencestoimmutableobjects,thenitisusually thecasethatnofieldsintheobjectreturnedbysuper.clone needtobemodified. ThemethodcloneforclassObjectperformsa specificcloningoperation.First,iftheclassofthisobjectdoes notimplementtheinterfaceCloneable,thena CloneNotSupportedExceptionisthrown.Notethatallarrays areconsideredtoimplementtheinterfaceCloneableandthat thereturntypeoftheclonemethodofanarraytypeT[] isT[]whereTisanyreferenceorprimitivetype. Otherwise,thismethodcreatesanewinstanceoftheclassofthis objectandinitializesallitsfieldswithexactlythecontentsof thecorrespondingfieldsofthisobject,asifbyassignment;the contentsofthefieldsarenotthemselvescloned.Thus,thismethod performsa"shallowcopy"ofthisobject,nota"deepcopy"operation. TheclassObjectdoesnotitselfimplementtheinterface Cloneable,socallingtheclonemethodonanobject whoseclassisObjectwillresultinthrowingan exceptionatruntime. Returns:acloneofthisinstance. Throws: CloneNotSupportedException-iftheobject'sclassdoesnot supporttheCloneableinterface.Subclasses thatoverridetheclonemethodcanalso throwthisexceptiontoindicatethataninstancecannot becloned.SeeAlso:Cloneable toString public String toString() Returnsastringrepresentationoftheobject.Ingeneral,the toStringmethodreturnsastringthat "textuallyrepresents"thisobject.Theresultshould beaconcisebutinformativerepresentationthatiseasyfora persontoread. Itisrecommendedthatallsubclassesoverridethismethod. ThetoStringmethodforclassObject returnsastringconsistingofthenameoftheclassofwhichthe objectisaninstance,theat-signcharacter`@',and theunsignedhexadecimalrepresentationofthehashcodeofthe object.Inotherwords,thismethodreturnsastringequaltothe valueof: getClass().getName()+'@'+Integer.toHexString(hashCode()) Returns:astringrepresentationoftheobject. notify publicfinal void notify() Wakesupasinglethreadthatiswaitingonthisobject's monitor.Ifanythreadsarewaitingonthisobject,oneofthem ischosentobeawakened.Thechoiceisarbitraryandoccursat thediscretionoftheimplementation.Athreadwaitsonanobject's monitorbycallingoneofthewaitmethods. Theawakenedthreadwillnotbeabletoproceeduntilthecurrent threadrelinquishesthelockonthisobject.Theawakenedthreadwill competeintheusualmannerwithanyotherthreadsthatmightbe activelycompetingtosynchronizeonthisobject;forexample,the awakenedthreadenjoysnoreliableprivilegeordisadvantageinbeing thenextthreadtolockthisobject. Thismethodshouldonlybecalledbyathreadthatistheowner ofthisobject'smonitor.Athreadbecomestheownerofthe object'smonitorinoneofthreeways: Byexecutingasynchronizedinstancemethodofthatobject. Byexecutingthebodyofasynchronizedstatement thatsynchronizesontheobject. ForobjectsoftypeClass,byexecutinga synchronizedstaticmethodofthatclass. Onlyonethreadatatimecanownanobject'smonitor. Throws: IllegalMonitorStateException-ifthecurrentthreadisnot theownerofthisobject'smonitor.SeeAlso:notifyAll(), wait() notifyAll publicfinal void notifyAll() Wakesupallthreadsthatarewaitingonthisobject'smonitor.A threadwaitsonanobject'smonitorbycallingoneofthe waitmethods. Theawakenedthreadswillnotbeabletoproceeduntilthecurrent threadrelinquishesthelockonthisobject.Theawakenedthreads willcompeteintheusualmannerwithanyotherthreadsthatmight beactivelycompetingtosynchronizeonthisobject;forexample, theawakenedthreadsenjoynoreliableprivilegeordisadvantagein beingthenextthreadtolockthisobject. Thismethodshouldonlybecalledbyathreadthatistheowner ofthisobject'smonitor.Seethenotifymethodfora descriptionofthewaysinwhichathreadcanbecometheownerof amonitor. Throws: IllegalMonitorStateException-ifthecurrentthreadisnot theownerofthisobject'smonitor.SeeAlso:notify(), wait() wait publicfinal void wait(long timeout) throwsInterruptedException Causesthecurrentthreadtowaituntileitheranotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject,ora specifiedamountoftimehaselapsed. Thecurrentthreadmustownthisobject'smonitor. Thismethodcausesthecurrentthread(callitT)to placeitselfinthewaitsetforthisobjectandthentorelinquish anyandallsynchronizationclaimsonthisobject.ThreadT becomesdisabledforthreadschedulingpurposesandliesdormant untiloneoffourthingshappens: Someotherthreadinvokesthenotifymethodforthis objectandthreadThappenstobearbitrarilychosenas thethreadtobeawakened. SomeotherthreadinvokesthenotifyAllmethodforthis object. Someotherthreadinterrupts threadT. Thespecifiedamountofrealtimehaselapsed,moreorless.If timeoutiszero,however,thenrealtimeisnottakeninto considerationandthethreadsimplywaitsuntilnotified. ThethreadTisthenremovedfromthewaitsetforthis objectandre-enabledforthreadscheduling.Itthencompetesinthe usualmannerwithotherthreadsfortherighttosynchronizeonthe object;onceithasgainedcontroloftheobject,allits synchronizationclaimsontheobjectarerestoredtothestatusquo ante-thatis,tothesituationasofthetimethatthewait methodwasinvoked.ThreadTthenreturnsfromthe invocationofthewaitmethod.Thus,onreturnfromthe waitmethod,thesynchronizationstateoftheobjectandof threadTisexactlyasitwaswhenthewaitmethod wasinvoked. Athreadcanalsowakeupwithoutbeingnotified,interrupted,or timingout,aso-calledspuriouswakeup.Whilethiswillrarely occurinpractice,applicationsmustguardagainstitbytestingfor theconditionthatshouldhavecausedthethreadtobeawakened,and continuingtowaitiftheconditionisnotsatisfied.Inotherwords, waitsshouldalwaysoccurinloops,likethisone: synchronized(obj){ while() obj.wait(timeout); ...//Performactionappropriatetocondition } (Formoreinformationonthistopic,seeSection3.2.3inDougLea's "ConcurrentProgramminginJava(SecondEdition)"(Addison-Wesley, 2000),orItem50inJoshuaBloch's"EffectiveJavaProgramming LanguageGuide"(Addison-Wesley,2001). Ifthecurrentthreadisinterruptedbyanythreadbeforeorwhileitiswaiting,thenan InterruptedExceptionisthrown.Thisexceptionisnot thrownuntilthelockstatusofthisobjecthasbeenrestoredas describedabove. Notethatthewaitmethod,asitplacesthecurrentthread intothewaitsetforthisobject,unlocksonlythisobject;any otherobjectsonwhichthecurrentthreadmaybesynchronizedremain lockedwhilethethreadwaits. Thismethodshouldonlybecalledbyathreadthatistheowner ofthisobject'smonitor.Seethenotifymethodfora descriptionofthewaysinwhichathreadcanbecometheownerof amonitor. Parameters:timeout-themaximumtimetowaitinmilliseconds. Throws: IllegalArgumentException-ifthevalueoftimeoutis negative. IllegalMonitorStateException-ifthecurrentthreadisnot theowneroftheobject'smonitor. InterruptedException-ifanythreadinterruptedthe currentthreadbeforeorwhilethecurrentthread waswaitingforanotification.Theinterrupted statusofthecurrentthreadisclearedwhen thisexceptionisthrown.SeeAlso:notify(), notifyAll() wait publicfinal void wait(long timeout, int nanos) throwsInterruptedException Causesthecurrentthreadtowaituntilanotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject,or someotherthreadinterruptsthecurrentthread,oracertain amountofrealtimehaselapsed. Thismethodissimilartothewaitmethodofone argument,butitallowsfinercontrolovertheamountoftimeto waitforanotificationbeforegivingup.Theamountofrealtime, measuredinnanoseconds,isgivenby: 1000000*timeout+nanos Inallotherrespects,thismethoddoesthesamethingasthe methodwait(long)ofoneargument.Inparticular, wait(0,0)meansthesamethingaswait(0). Thecurrentthreadmustownthisobject'smonitor.Thethread releasesownershipofthismonitorandwaitsuntileitherofthe followingtwoconditionshasoccurred: Anotherthreadnotifiesthreadswaitingonthisobject'smonitor towakeupeitherthroughacalltothenotifymethod orthenotifyAllmethod. Thetimeoutperiod,specifiedbytimeout millisecondsplusnanosnanosecondsarguments,has elapsed. Thethreadthenwaitsuntilitcanre-obtainownershipofthe monitorandresumesexecution. Asintheoneargumentversion,interruptsandspuriouswakeupsare possible,andthismethodshouldalwaysbeusedinaloop: synchronized(obj){ while() obj.wait(timeout,nanos); ...//Performactionappropriatetocondition } Thismethodshouldonlybecalledbyathreadthatistheowner ofthisobject'smonitor.Seethenotifymethodfora descriptionofthewaysinwhichathreadcanbecometheownerof amonitor. Parameters:timeout-themaximumtimetowaitinmilliseconds.nanos-additionaltime,innanosecondsrange 0-999999. Throws: IllegalArgumentException-ifthevalueoftimeoutis negativeorthevalueofnanosis notintherange0-999999. IllegalMonitorStateException-ifthecurrentthreadisnot theownerofthisobject'smonitor. InterruptedException-ifanythreadinterruptedthe currentthreadbeforeorwhilethecurrentthread waswaitingforanotification.Theinterrupted statusofthecurrentthreadisclearedwhen thisexceptionisthrown. wait publicfinal void wait() throwsInterruptedException Causesthecurrentthreadtowaituntilanotherthreadinvokesthe notify()methodorthe notifyAll()methodforthisobject. Inotherwords,thismethodbehavesexactlyasifitsimply performsthecallwait(0). Thecurrentthreadmustownthisobject'smonitor.Thethread releasesownershipofthismonitorandwaitsuntilanotherthread notifiesthreadswaitingonthisobject'smonitortowakeup eitherthroughacalltothenotifymethodorthe notifyAllmethod.Thethreadthenwaitsuntilitcan re-obtainownershipofthemonitorandresumesexecution. Asintheoneargumentversion,interruptsandspuriouswakeupsare possible,andthismethodshouldalwaysbeusedinaloop: synchronized(obj){ while() obj.wait(); ...//Performactionappropriatetocondition } Thismethodshouldonlybecalledbyathreadthatistheowner ofthisobject'smonitor.Seethenotifymethodfora descriptionofthewaysinwhichathreadcanbecometheownerof amonitor. Throws: IllegalMonitorStateException-ifthecurrentthreadisnot theowneroftheobject'smonitor. InterruptedException-ifanythreadinterruptedthe currentthreadbeforeorwhilethecurrentthread waswaitingforanotification.Theinterrupted statusofthecurrentthreadisclearedwhen thisexceptionisthrown.SeeAlso:notify(), notifyAll() finalize protected void finalize() throwsThrowable Calledbythegarbagecollectoronanobjectwhengarbagecollection determinesthattherearenomorereferencestotheobject. Asubclassoverridesthefinalizemethodtodisposeof systemresourcesortoperformothercleanup. Thegeneralcontractoffinalizeisthatitisinvoked ifandwhentheJavaTMvirtual machinehasdeterminedthatthereisnolongerany meansbywhichthisobjectcanbeaccessedbyanythreadthathas notyetdied,exceptasaresultofanactiontakenbythe finalizationofsomeotherobjectorclasswhichisreadytobe finalized.Thefinalizemethodmaytakeanyaction,including makingthisobjectavailableagaintootherthreads;theusualpurpose offinalize,however,istoperformcleanupactionsbefore theobjectisirrevocablydiscarded.Forexample,thefinalizemethod foranobjectthatrepresentsaninput/outputconnectionmightperform explicitI/Otransactionstobreaktheconnectionbeforetheobjectis permanentlydiscarded. ThefinalizemethodofclassObjectperformsno specialaction;itsimplyreturnsnormally.Subclassesof Objectmayoverridethisdefinition. TheJavaprogramminglanguagedoesnotguaranteewhichthreadwill invokethefinalizemethodforanygivenobject.Itis guaranteed,however,thatthethreadthatinvokesfinalizewillnot beholdinganyuser-visiblesynchronizationlockswhenfinalizeis invoked.Ifanuncaughtexceptionisthrownbythefinalizemethod, theexceptionisignoredandfinalizationofthatobjectterminates. Afterthefinalizemethodhasbeeninvokedforanobject,no furtheractionistakenuntiltheJavavirtualmachinehasagain determinedthatthereisnolongeranymeansbywhichthisobjectcan beaccessedbyanythreadthathasnotyetdied,includingpossible actionsbyotherobjectsorclasseswhicharereadytobefinalized, atwhichpointtheobjectmaybediscarded. ThefinalizemethodisneverinvokedmorethanoncebyaJava virtualmachineforanygivenobject. Anyexceptionthrownbythefinalizemethodcauses thefinalizationofthisobjecttobehalted,butisotherwise ignored. Throws: Throwable-theExceptionraisedbythismethod Overview Package Class Use Tree Deprecated Index Help Java™ PlatformStandard Ed. 7 PrevClass NextClass Frames NoFrames AllClasses Summary:  Nested |  Field |  Constr |  Method Detail:  Field |  Constr |  Method SubmitabugorfeatureForfurtherAPIreferenceanddeveloperdocumentation,seeJavaSEDocumentation.Thatdocumentationcontainsmoredetailed,developer-targeteddescriptions,withconceptualoverviews,definitionsofterms,workarounds,andworkingcodeexamples.Copyright©1993,2020,Oracleand/oritsaffiliates.Allrightsreserved.Useissubjecttolicenseterms.Alsoseethedocumentationredistributionpolicy.



請為這篇文章評分?