♧ Object类是比较特殊的类,它是所有类的父类。主要提供了11个方法(JDK 1.8为例):
/** * native方法,用于返回当前运行时对象的Class对象,使用final关键字修饰,子类不允许进行重写 */ public final native Class<?> getClass(); /** * native方法,用于返回对象的哈希码值,主要应用于哈希表中,比如JDK中的HashMap集合类 */ public native int hashCode(); /** * 用于比较两个对象的内存地址是否相同,如果要进行自定义比较,需要对该方法进行重写,比如String类中的equals方法就是比较字符串是否相同 */ public boolean equals(Object obj) { return (this == obj); } /** * native方法,用于创建并返回当前对象的一个拷贝。一般情况下,对于任何对象x,表达式x.clone() != x为true;x.clone().getClass() == x.getClass()为true。Object本身没有重写Cloneable接口,所以不重写clone方法就进行调用的时候,会抛出异常。 */ protected native Object clone() throws CloneNotSupportedException; /** * 返回类的名字@实例的哈希码的十六进制字符串 */ public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } /** * native方法,并且不能重写,唤醒一个在此对象监视器上等待的线程(监视器相当于锁的概念)。如果存在多个线程在等待,只会任意唤醒一个 */ public final native void notify(); /** * native方法,并且不能重写,唤醒在此对象监视器上等待的所有线程 */ public final native void notifyAll(); /** * native方法,并且不能重写。暂停线程的执行。注意:sleep方法没有释放锁,而wait方法释放了锁,timeout是等待时间 */ public final native void wait(long rimeout) throws InterrupteException; /** * wait方法重载,多了参数nanos,表示额外的时间(以毫秒为单位,范围是0-999999)。所以超时的时间需要加上nanos毫秒数 */ public final void wait(long timeout, int nanos) throws InterruptedException { if(timeout < 0) { throw new IllegalArgumentException("timeout value is negative"); } if(nanos < 0 || nanos > 999999) { throw new IllegalArgumentException("nanosecond timeout value out of range"); } if(nanos > 0) { timeout++; } wait(timeout); }
public final void wait() throws InterrupteException {
wait(0);
};
/**
* 实例被垃圾回收器回收的时候触发
*/ protected void finalize() throws Throwable {}