Object (Java Platform SE 7 ) - Oracle Help Center
文章推薦指數: 80 %
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(
延伸文章資訊
- 1Object (Java Platform SE 7 ) - Oracle Help Center
Class Object is the root of the class hierarchy. Every class has Object as a superclass. All obje...
- 2Objects and Classes in Java - Javatpoint
A class is a group of objects which have common properties. It is a template or blueprint from wh...
- 3Java Classes and Objects - W3Schools
Java is an object-oriented programming language. Everything in Java is associated with classes an...
- 4Java Object Class - Javatpoint
- 5Classes and Objects in Java - GeeksforGeeks
A class is a user defined blueprint or prototype from which objects are created. It represents th...