衆所周知,Object類是Java所有類的父類,所有的類(Object除外)都默認繼承了Object類。根據繼承的特點,父類的public方法可以在子類中使用,由此想來,作爲萬類之父的Object,所設計的方法應該是具有普遍性的。我翻閱了一下Object類的API和Object類的源碼,概括了一下,Object類一些方法。
Object 類的源碼:(註釋已經去掉了)
package java.lang;
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
public final native Class<?> getClass();
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
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 >= 500000 || (nanos != 0 && timeout == 0)) {
timeout++;
}
wait(timeout);
}
public final void wait() throws InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
首先是關於線程的幾個方法:
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException ;
public final void wait() throws InterruptedException ;
這些方法的底層都是native方法,是對底層線程的操作的方法。
然後是我們比較常用的一些方法:
public final native Class<?> getClass(); 反射的時候用到
public boolean equals(Object obj) ; 比較兩個對象是否相等,經常用到
public String toString() ; 常用的toString()方法
還有一些方法,似乎很少用到:
public native int hashCode();返回一個對象的哈希碼
protected native Object clone() throws CloneNotSupportedException; 克隆對象
protected void finalize() throws Throwable ;關於java垃圾收集器的方法