Object类是java程序中所有类的直接或者间接父类,处在类的最高层次。一个类在声明时若不包含关键字extends,系统就会认为该类就会直接继承Object类。Object类包含了所有java类的公共属性和方法,这些属性和方法在任何类中均可以直接使用。
package java.lang;
/**
* Class {@code Object} is the root of the class hierarchy.
* Every class has {@code Object} as a superclass. All objects,
* including arrays, implement the methods of this class.
*
* @author unascribed
* @see java.lang.Class
* @since JDK1.0
*/
public class Object {
……
}
Object类中的常用方法,这个面试经常会被问到:
【1】返回此Object的运行时类
public final native Class<?> getClass();
【2】hashCode的常规协定是:
1.在java应用程序执行期间,在对同一对象多次调用hashCode()方法时,必须一致地返回相同的整数,前提是将对象进行equals比较时所用的信息没有被修改。从某一应用程序的一次执行到同一应用程序的另一次执行,该整数无需保持一致。
2.如果根据equals(object)方法,两个对象是相等的,那么对这两个对象中的每个对象调用hashCode方法都必须生成相同的整数结果。
3.如果根据equals(java.lang.Object)方法,两个对象不相等,那么对这两个对象中的任一对象上调用hashCode()方法不要求一定生成不同的整数结果。但是,程序员应该意识到,为不相等的对象生成不同整数结果可以提高哈希表的性能。
public native int hashCode();
比较对象的内存地址
public boolean equals(Object obj) {
return (this == obj);
}
返回该对象的字符串表示,非常重要的方法
getClass().getName();获取字节码文件的对应全路径名例如java.lang.Object
Integer.toHexString(hashCode());将哈希值转成16进制数格式的字符串。
public String toString(){
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
本地clone方法,用于对象的复制
protected native Object clone() throws CloneNotSupportedException;
唤醒在此对象监视器上等待的单个线程
public final native void notity();
唤醒在此对象监视器上等待的所有线程
public final native void notifyAll();
在其他线程调用此对象的notify()方法或notifyAll()方法,或者超过指定的时间量前,导致当前线程等待
public final void wait() throws InterruptedException(){
wait(0);
}
public final native void wait(long timeout) throws InterruptedException;
当垃圾回收期确定不存在对该对象的更多引用时,由对象的垃圾回收器调用此方法。
protected void finalize() throws Throwable{}