概述
Object是所有类的基类,属于java.lang包。
构造方法
只有编译器提供的默认构造方法。
字段
Object类中没有成员字段。
方法
Object类一共12个方法。
按照访问等级分:
- public: getClass()、hashCode()、equals(Object obj)、toString()、notify()、notifyAll()、wait(long timeout)、wait(long timeout, int nanos)、wait()
- protected: clone()、finalize()
- private: registerNatives()
按照是否为final分:
- final:getClass()、notify()、notifyAll()、wait(long timeout)、wait(long timeout, int nanos)、wait()
- 非final:registerNatives()、hashCode()、equals(Object obj)、clone()、toString()、finalize()
按照是否为native分:
- native:registerNatives()、getClass()、hashCode()、clone()、notify()、notifyAll()、wait(long timeout)
- 非native:equals(Object obj)、toString()、wait(long timeout, int nanos)、wait()、finalize()
registerNatives()
private static native void registerNatives();
static {
registerNatives();
}
在初始化调用static代码块时调用,用于注册Object类中的所有本地方法。
getClass()
public final native Class<?> getClass();
返回类对象的Class实例,synchronized静态代码块时锁定的正是Class实例对象。
hashCode()、equals(Object obj)
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
hashCode()返回一个带符号int,返回一个对象实例的hashCode,其值可能是对象的存储地址;equals方法用来判断两个对象是否相等。
Java规范中对hashCode、equals方法有如下规范:
- hashCode相等,equals不一定为true
- equal方法为true,hashCode一定相等
- hashCode不想等,equals一定不为true
- equals方法为false,hashCode可能相等
重写equals(Object obj)方法时必须同时重写hashCode()方法
clone()
protected native Object clone() throws CloneNotSupportedException;
- 用于对java对象进行复制,可分为深复制和浅复制。
- 如果对象未实现Cloneable接口,会抛出CloneNotSupportedException异常
toString()
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
默认实现为Class名+"@"+十六进制的hashCode
多线程相关notify()、notifyAll()、wait(long timeout)、wait(long timeout, int nanos)、wait()
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
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);
}
- notify():唤醒一个正在等待这个对象的monitor线程,如果有多个线程在等待,只能唤醒其中一个
- notifyAll():唤醒所有在等待这个对象的monitor线程
-
wait(long timeout):将当前持有此对象锁的线程进入等待状态,直到线程被notify()、notifyAll()、Thread.interrupts()方法唤醒或者超时。
- 如果timeout为0,则会一直等待,直到被另外唤醒
- wait(long timeout, int nanos):与wait(long timeout)类似,但添加了一个nanos参数以提供更细粒度的等待时间控制
- wait():默认当前持有对象锁的线程进入等待状态并一直等待直到被notify()、notifyAll()、Thread.interrupts()方法唤醒
finalize()
protected void finalize() throws Throwable { }
在GC回收对象实例时会被调用,因GC是不确定且随机的,无法确定此方法的执行时间(如果内存充足,GC永远都不会发生则finalize()方法一直都不会被调用)。
个人博客:http://magictan.cn
欢迎扫码关注我微信公众号:magicTan。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。