Object类

在Java中Object类是所有类的直接或间接父类,也就是说,所有类都继承了它的一些方法,简单来看一下这些方法的使用

toString

在熟知的System.out.println方法内部,打印一个对象,就会调用该对象的toString方法,这里我贴一下println(obj)的源码

public void println(Object x) {
    String s = String.valueOf(x);
     synchronized (this) {
        print(s);
        newLine();
    }
}

public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }

可以看一下Object中的toString方法是怎样的

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

也就是说要使用sout打印一个对象时,究竟要打印出什么,可以由程序员自己决定,实现手段就是重写toString方法
一个类如果没有重写toString方法,那么默认打印出的就是类名@十六进制哈希值的形式(稍后解释)

hashCode

public native int hashCode();

在Object类中,hashCode是一个native方法,返回值为int,该方法在外部定义,我们不知道它的实现(实际上与对象的内存地址有关),但通过注解我们能知道它的规则。
它有三个contract(合约)

  1. Whenever it is invoked on the same object more than once during an execution of a Java application, the {@code hashCode} method must consistently return the same integer, provided no information used in {@code equals} comparisons on the object is modified.This integer need not remain consistent from one execution of an application to another execution of the same application.
    在同一次执行中,两个相同对象的hashCode相同,在同一应用程序的一次执行与另一次执行之间,此整数不必保持一致。
  2. If two objects are equal according to the {@code equals(Object)} method, then calling the {@code hashCode} method on each of the two objects must produce the same integer result.
    如果根据equals方法,两个对象相等,那么对两个对象中的hashCode方法必须产生相同的整数结果。
  3. It is not required that if two objects are unequal according to the {@link java.lang.Object#equals(java.lang.Object)} method, then calling the {@code hashCode} method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
    如果根据{@link java.lang.Object#equals(java.lang.Oobject)}方法,两个对象不相等,那么对这两个对象中的每一个调用{@code hashCode}方法都必须产生不同的整数结果。

equals

equals方法用于判断两个对象是否相等,这里不得不提一下 ==
对基本数据类型,比较的是其内部值
对引用数据类型,比较的就是它们在内存中的存放地址了,这显然会出现许多问题
可以看一下Object中的equals方法

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

实际上就是==运算符,所以往往我们需要根据需求,在类中重写equals方法。
很多封装方法的实现都是基于equals方法,只要涉及到比较
包括也和上面的hashCode的实现有关,equals的两个对象hashCode相同

getClass

public final native Class<?> getClass();

getClass也是一个native方法,返回的是Class字节码对象
见名知意,返回的就是该类的Class字节码对象

notify && notifyAll

wait

这三个和多线程相关,以后再补充