Object的描述
Object类是类层次结构的根,每个类都有Object类作为超类,所有对象(包括数组)都实现了这个类的方法
Object类的toString方法
toString源码
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
我们可以重写同String方法
创建一个Student类
public class Student {
public String name;
public int age;
//添加属性的setter和getter方法
public class ObjectDemo {
public static void main(String[] args) {
Student student=new Student();
System.out.println(student.toString());
}
}
运行Object类,结果如下
在原来的Student类添加同String方法
Object类的equals方法
public class ObjectDemo {
public static void main(String[] args) {
Student student=new Student();
System.out.println(student.toString());
//需求:比较两个对象的内容是否相同
Student student1=new Student();
System.out.println(student==student1);
}
}
运行后结果是false还是true?
但是改为,结果仍为false
System.out.println(student.equals(student1));
查看equals源码
public boolean equals(Object obj) {
return (this == obj);
}
可以发现此时就是==,所以仍然需要重写equals方法
@Override
public boolean equals(Object o) {
//比较地址是否相同 如果相同 就为null
if (this == o) return true;
//判断参数是否为null
//判断两个对象是来自同一个类
if (o == null || getClass() != o.getClass()) return false;
//向下转型
Student student = (Student) o;
//比较年龄是否相同
if (age != student.age) return false;
//比较姓名内容是否相同
return name != null ? name.equals(student.name) : student.name == null;
}
在运行就是true