Analysis of java Object class

In Java, Object is the parent class of all classes, and any class inherits Object by default. The methods it provides mainly include the following:

package java.lang;

/**
 * JDK1.8
 */
public class Object {

	// native关键字表示此方法通过JNI(java native interface)接口调用C/C++ 语言实现对底层的访问
    private static native void registerNatives();
    static {
        registerNatives();
    }

	// final 说明getClass()是不能被子类重写,保证一个子类有多重继承关系时, 其调用getClass()方法与其父类调用getClass()方法的表现一致
    public final native Class<?> getClass();

	// 表示该对象的哈希码值,整型
    public native int hashCode();

	// 比较当前对象与传入的对象在内存中的存放地址是否相同
    public boolean equals(Object obj) {
        return (this == obj);
    }

	// 返回一个被拷贝对象的引用,此对象与原对象分别占用不同的堆空间;注意:调用clone()需要实现Cloneable接口,如果没有实现Cloneable接口,并且子类直接调用Object类的clone()方法,会抛出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();

	//  等待时间(以毫秒为单位),如果timeout毫秒内没有通知就超时返回;如果当前线程在等待之前或在等待时被任何线程中断,则会抛出 InterruptedException 异常
    public final native void wait(long timeout) throws InterruptedException;
	
	// 该方法与 wait(long timeout) 方法类似,多了一个 nanos 参数,这个参数表示额外时间(以纳秒为单位,范围是 0-999999), 所以超时的时间还需要加上 nanos 纳秒。
    public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {    //如果传递的参数不合法,则会抛出 IllegalArgumentException 异常
            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);
    }
	
	// 让当前线程进入等待状态,直到其他线程调用此对象的 notify()方法或 notifyAll()方法
    public final void wait() throws InterruptedException {
        wait(0);   // timeout 参数为 0,则不会超时,会一直进行等待
    }

	// GC在内存不足时进行垃圾回收 或者 System.gc()强制垃圾回收时,调用此方法
    protected void finalize() throws Throwable { }
}

Record it, if it is helpful, remember to like it three times~

Supongo que te gusta

Origin blog.csdn.net/qq_33539839/article/details/115210000
Recomendado
Clasificación