Java重写父equals方法
我有两个班,分别是Java重写父equals方法,java,Java,我有两个班,分别是人和老师。在Person类中,我使用compareTo方法检查传入的两个对象是否相等。在Teacher类中,我正在处理的问题表明我需要亲自重写equals方法。在这个equals方法中,如果Person中的equals方法和Teacher中的equals方法都相等,那么它将返回true。我的问题是,当我检查Teacher的equals方法时,我是否只是调用super.equals(other)来检查父类是否将这两个对象相等,或者我是否需要做其他事情 人: public clas
人
和老师
。在Person
类中,我使用compareTo方法检查传入的两个对象是否相等。在Teacher
类中,我正在处理的问题表明我需要亲自重写equals
方法。在这个equals
方法中,如果Person
中的equals
方法和Teacher
中的equals
方法都相等,那么它将返回true。我的问题是,当我检查Teacher
的equals
方法时,我是否只是调用super.equals(other)
来检查父类是否将这两个对象相等,或者我是否需要做其他事情
人:
public class Person implements Comparable<Person> {
public boolean equals(Object other) {
try {
return this.compareTo(other) == 0;
}catch(Exception e) {
return false;
}
}
}
基本上,国家契约: 它是对称的:对于任何非空的引用值x和y,当且仅当y.equals(x)返回true时,x.equals(y)才应返回true 而
Teacher#equals
的实现不符合这一要求。对于在继承自非对象的类中实现equals
方法的情况,例如教师
,您应该验证要比较的对象的类型是否与要比较的类相同。要实现这一点,应使用getClass().equals
:
public class Teacher extends Person {
private String facultyID;
@Override
public boolean equals(Object other) {
//this line is nonsense, not all Persons are Teachers
//boolean personEquals = super.equals(other);
//avoid using try-catch
//try {
//verify that the other object is not null
if (other == null) {
return false;
}
//verify that the other object is specifically a Teacher, not a super or a subclass of it
if (this.getClass().equals(other.getClass()) {
//here comes the real check
Teacher otherTeacher = (Teacher)other;
return this.facultyID.equals(otherTeacher.facultyID);
}
return false;
}
}
对Person
执行类似操作,以防它不允许与它的子类进行比较。此操作。compareTo(其他)
不会返回布尔值。这应该是this.compareTo(other)==0
。对于的两个相互竞争的实现要非常小心。这样会导致非对称相等。@CostiCiudatu感谢您的帮助!我编辑了代码以改变这种情况。@khelwood我正在学习CS期末考试,其中一个问题要求我编写一个equals方法来重写父类中的方法。但是,谢谢你的提醒@Andrew khelwood所说的是指部分指定它是对称的:对于任何非空引用值x和y,x.equals(y)应该返回true,当且仅当y.equals(x)返回true。
public class Teacher extends Person {
private String facultyID;
@Override
public boolean equals(Object other) {
//this line is nonsense, not all Persons are Teachers
//boolean personEquals = super.equals(other);
//avoid using try-catch
//try {
//verify that the other object is not null
if (other == null) {
return false;
}
//verify that the other object is specifically a Teacher, not a super or a subclass of it
if (this.getClass().equals(other.getClass()) {
//here comes the real check
Teacher otherTeacher = (Teacher)other;
return this.facultyID.equals(otherTeacher.facultyID);
}
return false;
}
}