📅  最后修改于: 2020-09-24 05:35:21             🧑  作者: Mango
默认情况下,Object类是Java中所有类的父类。换句话说,它是Java的最高类。
如果要引用其类型未知的任何对象,则Object类很有用。请注意,父类引用变量可以引用子类对象,称为向上转换。
让我们举个例子,有一个getObject()方法返回一个对象,但是它可以是任何类型,例如Employee,Student等,我们可以使用Object类引用来引用该对象。例如:
"Object obj=getObject();//we don't know what object will be returned from this method
Object类为所有对象提供了一些常见的行为,例如可以比较对象,可以克隆对象,可以通知对象等。
The Object class provides many methods. They are as follows: |
Method | Description |
---|---|
public final Class getClass() | returns the Class class object of this object. The Class class can further be used to get the metadata of this class. |
public int hashCode() | returns the hashcode number for this object. |
public boolean equals(Object obj) | compares the given object to this object. |
protected Object clone() throws CloneNotSupportedException | creates and returns the exact copy (clone) of this object. |
public String toString() | returns the string representation of this object. |
public final void notify() | wakes up single thread, waiting on this object’s monitor. |
public final void notifyAll() | wakes up all the threads, waiting on this object’s monitor. |
public final void wait(long timeout)throws InterruptedException | causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait(long timeout,int nanos)throws InterruptedException | causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method). |
public final void wait()throws InterruptedException | causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method). |
protected void finalize()throws Throwable | is invoked by the garbage collector before object is being garbage collected. |
在下一章中,我们将详细学习这些方法。