Java的定義:萬物皆對象
Java把現實中的任何事物都當做一個對象(Object), Java是面向對象的,就是Object Orentied 簡稱OO 。
此處的Object在Java中被定義爲一個頂級父類,它是任何類父類,我們可以顯示的繼承它,也可以隱式繼承。
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
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 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 InterruptedException {
wait(0);
}
protected void finalize() throws Throwable { }
}
Object類裏邊對應的方法都代表什麼意思?
-
clone() 複製
public class Student implements Cloneable { String name; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } public Student(String name){ this.name = name; } }
Student stu1 = new Student("張三"); Student stu2 = (Student)stu1.clone();
-
getClass() 獲取對象的class(反射使用)
-
equals() 對象值比較,重寫equals方法必須重寫hashcode,對象的約定,例如不重寫,hashMap的kv不一致;
@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }
爲什麼重寫equals必須重寫hashcode?
不重寫hashcode,Object默認的hashcode將對象的內存地址經過哈希算法返回給我們一個int,就違反了兩個對象相等,hashcode一定相等的規定 -
hashCode() 對象的hash值
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; }
兩個對象相等,hashcode一定相等
兩個對象不等,hashcode不一定不等
hashcode相等,兩個對象不一定相等(“A1”、“B1”)
hashcode不等,兩個對象一定不等 -
tostring() 把引用數據類型轉換成字符串。直接打印一個引用數據類型的對象則默認調用這個對象動態toString方法。
-
notify() 此方法能夠喚醒一個正在等待該對象的monitor的線程,當有多個線程都在等待該對象的monitor的話,則只能喚醒其中一個線程,具體喚醒哪個線程則不得而知
-
notifyall() 此方法能夠喚醒所有正在等待該對象的monitor的線程,這一點與notify()方法是不同的。
-
wait() 此方法,相當於讓當前線程交出此對象的monitor,然後進入等待狀態,等待後續再次獲得此對象的鎖
-
finalize() 裏面的邏輯會在當前對象被垃圾回收器回收的時候執行。