s-day01-Object类的自动重写equals方法
This commit is contained in:
@@ -15,6 +15,9 @@ public boolean equals(Object obj) {
|
||||
}
|
||||
如果父类的内容比较功能,不符合子类(Student)的需求,那就重写equals方法
|
||||
|
||||
总结:每个对象的equals方法继承自Object类,默认使用==比较地址值,这个对于我们而言,不满足咱们需求
|
||||
因此我们会在每个类中重写equals方法,不用手动写,直接alt+insert自动生成
|
||||
|
||||
|
||||
*/
|
||||
public class Demo03 {
|
||||
@@ -25,7 +28,7 @@ public class Demo03 {
|
||||
|
||||
//创建2个学生对象(内容相同的2个对象,看作是同一个)
|
||||
Student stu1 = new Student("张三", 18);
|
||||
Student stu2 = new Student("张三", 18);
|
||||
Student stu2 = new Student("张三", 19);
|
||||
System.out.println(stu1 == stu2);//false
|
||||
System.out.println(stu1.equals(stu2));//true!
|
||||
}
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
package com.inmind.object01;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
//间接继承Object类
|
||||
public class Student extends Object{
|
||||
String name;
|
||||
@@ -21,7 +24,16 @@ public class Student extends Object{
|
||||
}
|
||||
|
||||
//重写equals方法,不要比较地址,比较内容
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
|
||||
Student student = (Student) o;
|
||||
return age == student.age && Objects.equals(name, student.name);
|
||||
}
|
||||
|
||||
/*@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj) {
|
||||
return true;//地址相同,内容相同
|
||||
@@ -38,5 +50,7 @@ public class Student extends Object{
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}*/
|
||||
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user