Java 重写Object类中的方法会带来的问题

Object类主要方法有:
1.getClass();返回此对象的运行时类。
2.hashCode();返回对象的哈希码值
3.toString();返回对象的字符串表示形式
4.equalis();判断对象是否相等
5.wait();使当前线程处于等待状态,直到等到另一个线程调用notify()或者notifyAll();
6.notify();唤醒正在等待的单个线程。
7.notifyAll();唤醒正在等待的所有线程。
8.finalize();垃圾回收会调用此方法。

创建一个Student类,不重写Object类的任何方法。
调用toString();查看源码:

public class TestObject {
    public static void main(String[] args) {
        Object object=new Object();
        String name=new String("aaa");
        Student student=new Student();
        System.out.println(student.toString());
    }
}
class Student{
    private String name;
    private int age;
}

toString()源码:

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

可以看出,toString()方法又调用了hashCode()方法。所以说,当你重写了hashCode()的方法,一定要重写toString()方法,但是重写了toString()的方法,可以不用重写hashCode()的方法

猜你喜欢

转载自blog.csdn.net/m0_45196258/article/details/107793699