Object中有哪些方法?

有一种遗憾就是,每天都见到你,但是却不关注你!等到面试的时候才后悔莫及。

Object类中有9大public方法:

equals:判断两个对象"相等"

hashCode:获取对象的哈希值

toString:把对象转为字符串

getClass:返回运行时的class,这个方法在Object中是个native方法。

以下5个都和多线程有关系。

notify

notifyAll

wait

wait(long timeout)

wait(long timeout, int nanos)

2个protected方法:

clone:

finalize:

1个private方法

registerNatives: 详细不知道是啥

下面来详细地学习一下这几个方法。

public boolean equals(java.lang.Object obj)

public boolean equals(java.lang.Object obj) {
    return (this == obj);
}

Object里面的equals方法挺简单的,就是比较两个对象的引用是否相等。

public native int hashCode()

Object里面的hashCode居然是个native方法。

public String toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

public final native Class<?> getClass()

这个getClass也是个本地方法,还是final的。

/**
  * Returns the runtime class of this {@code Object}. The returned
  * {@code Class} object is the object that is locked by {@code
  * static synchronized} methods of the represented class.
  *
  * <p><b>The actual result type is {@code Class<? extends |X|>}
  * where {@code |X|} is the erasure of the static type of the
  * expression on which {@code getClass} is called.</b> For
  * example, no cast is required in this code fragment:</p>
  *
  * <p>
  * {@code Number n = 0;                             }<br>
  * {@code Class<? extends Number> c = n.getClass(); }
  * </p>
  *
  * @return The {@code Class} object that represents the runtime
  *         class of this object.
  * @jls 15.8.2 Class Literals
  */

protected native java.lang.Object clone() throws CloneNotSupportedException

克隆对象

protected void finalize() throws Throwable { }

private static native void registerNatives()

猜你喜欢

转载自www.cnblogs.com/tuhooo/p/9057308.html