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() 里面的逻辑会在当前对象被垃圾回收器回收的时候执行。