java原始碼學習 --object
阿新 • • 發佈:2020-08-18
Object類是一切類的祖宗
所有的類都預設繼承Object類
private static native void registerNatives(); static { //靜態程式碼塊,只執行一次 registerNatives(); }
當原始碼中,當一個方法以" ; "結尾,沒由{},且修飾符列表中由"native"關鍵字,表示底層呼叫c++寫的dll程式(dll:動態連結庫檔案)
getClass()
public final native Class<?> getClass();//底層呼叫c++
hashCode()
publicnative int hashCode();//也是底層呼叫c++ 據說1.8添加了很多有意思的特性,要學習學習,瞭解瞭解
equals(Object obj)
public boolean equals(Object obj) { return (this == obj); }//equals其實也是用==實現的,其實是為了給我們重寫用的
clone()
protected native Object clone() throws CloneNotSupportedException;//已經有了一個物件a,可以用clone()方法建立一個一模一樣的
toString()//終於又碰到一個能用的了
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); }//例項方法非靜態
試一試看看是什麼
package com.xuyifan.LearnObject; /** * @author xyf * @create 2020-08-18-13:50 */ public class demo02 { public static void main(String[] args) { demo02 demo02=new demo02(); String returnString=demo02.toString(); System.out.println(returnString);
System.out.println(demo02); } }
輸出
com.xuyifan.LearnObject.demo02@1540e19d// "@" 前面的是類的名字,"@"後面是物件在堆中的實體地址經過 雜湊演算法 得到的十六進位制數字
com.xuyifan.LearnObject.demo02@1540e19d // 我們在是由System.out.print(引用時)時,print會自動呼叫該引用的toString();方法
notify()
public final native void notify();
notifyAll()
public final native void notifyAll();
wait(long timeout)
public final native void wait(long timeout) throws InterruptedException;
wait(long timeout, int 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); }
wait()
public final void wait() throws InterruptedException { wait(0); }
finalize()
protected void finalize() throws Throwable { }
這就是萬類之祖,Object類