為什麼Object類是Java中所有類的超類?
Java.lang.Object 類是類層次結構的根或超類,它位於java.lang包中。所有預定義類和使用者定義類都是Object類的子類。
為什麼Object類是超類
可重用性
- 每個物件都有11個共同屬性,這些屬性必須由每個Java開發人員實現。
- 為了減輕開發人員的負擔,SUN開發了一個名為Object的類,它用11個方法實現了這11個屬性。
- 所有這些方法都具有對所有子類通用的邏輯,如果此邏輯不滿足子類的需求,則子類可以覆蓋它。
執行時多型性
- 為了實現執行時多型性,以便我們可以編寫單個方法來接收和傳送任何型別的類物件作為引數和返回型別。
每個類物件的通用功能
比較兩個物件
- public boolean equals(Object obj)
獲取雜湊碼
- public int hashCode()
檢索執行時類物件引用
- public final Class getClass()
以字串格式檢索物件資訊
- public String toString()
克隆物件
- protected Object clone() throws CloneNotSupportedException
物件清理程式碼/資源釋放程式碼
- protected void finalize() throws Throwable
等待當前執行緒,直到另一個執行緒呼叫notify()
- public final void wait() throws InterruptedException
等待當前執行緒,直到另一個執行緒在指定時間內呼叫notify()
- public final void wait(long timeout) throws InterruptedException
等待當前執行緒,直到另一個執行緒在指定時間內呼叫notify()
- public final void wait(long timeout, int nano) throws InterruptedException
通知等待執行緒物件鎖可用
- public final void notify()
通知所有等待執行緒物件鎖可用
- public final void notifyAll()
示例
class Thing extends Object implements Cloneable { public String id; public Object clone() throws CloneNotSupportedException { return super.clone(); } public boolean equals(Object obj) { boolean result = false; if ((obj!=null) && obj instanceof Thing) { Thing t = (Thing) obj; if (id.equals(t.id)) result = true; } return result; } public int hashCode() { return id.hashCode(); } public String toString() { return "This is: "+id; } } public class Test { public static void main(String args[]) throws Exception { Thing t1 = new Thing(), t2; t1.id = "Raj"; t2 = t1; // t1 == t2 and t1.equals(t2) t2 = (Thing) t1.clone(); // t2!=t1 but t1.equals(t2) t2.id = "Adithya"; // t2!=t1 and !t1.equals(t2) Object obj = t2; System.out.println(obj); //Thing = Adithya } }
輸出
This is: Adithya
廣告