Object介绍
Object类是所有Java类的祖先。每个类(包括数组)都使用Object作为超类。
在不明确给出超类的情况下,Java会自动把Object作为要定义类的超类。
可以使用类型为Object的变量指向任意类型的对象。
Object类有一个默认构造方法pubilc Object(),在构造子类实例时,都会先调用这个默认构造方法。
查看源码
package java.lang;
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
// 返回该对象的Class对象。
public final native Class<?> getClass();
// 返回一个和对象地址相关的整形散列码。
public native int hashCode();
// 比较两个对象地址是否相同。
public boolean equals(Object obj) {
return (this == obj);
}
// 实现对象的浅复制,只有实现了Cloneable接口才可以使用该方法,否则抛出CloneNotSupportedException异常。
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;
// 重载方法,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);
}
// 重载方法,该方法没有超时时间,只能被唤醒。
public final void wait() throws InterruptedException {
wait(0);
}
// 该方法通常用于释放资源, GC在回收对象之前调用该方法,很少使用。
protected void finalize() throws Throwable { }