[英]Java overriding parent equals method
I have two classes Person
and Teacher
. 我有两班Person
及Teacher
。 In the Person
class I check if the two objects passed in are equal using the compareTo method. 在Person
类中,我使用compareTo方法检查传入的两个对象是否相等。 In the Teacher
class, the problem I'm working on states that I need to override the equals
method in Person. 在“ Teacher
课程中,我正在处理的问题表明我需要覆盖Person中的equals
方法。 In this equals
method, the only way it would return true is if it's equal in both the equals
method in Person
and Teacher
. 在此equals
方法中,返回true的唯一方法是在Person
和Teacher
的equals
方法中是否相等。 My question is, when I check in the Teacher
's equals
method, do I just call super.equals(other)
in order to check if the two objects are equal by the parent class or is there something else I need to do? 我的问题是,当我签入Teacher
的equals
方法时,是否只调用super.equals(other)
以便检查父类是否两个对象相等,或者还有其他需要做的事情吗?
Person: 人:
public class Person implements Comparable<Person> {
public boolean equals(Object other) {
try {
return this.compareTo(other) == 0;
}catch(Exception e) {
return false;
}
}
}
Teacher 老师
public class Teacher extends Person {
private String facultyID;
@Override
public boolean equals(Object other) {
boolean personEquals = super.equals(other);
try {
Teacher teach1 = (Teacher)other;
boolean idEquals = this.facultyID.equals(teach1.facultyID);
if(idEquals && personEquals)
return true;
return false;
}catch(Exception e) {
return false;
}
}
}
Basically, the contract of Object#equals
states: 基本上, Object#equals
的合同规定:
It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true 它是对称的:对于任何非空参考值x和y,当且仅当y.equals(x)返回true时,x.equals(y)才应返回true。
And the implementation of Teacher#equals
doesn't meet this requirement. 而且Teacher#equals
的实现不满足此要求。 For cases when implementing equals
method in a class that inherits from another that is not Object
eg Teacher
, you should verify if the type of the object to be compared is the same as the class you're comparing. 对于在从不是Object
其他类(例如Teacher
继承的类中实现equals
方法的情况,您应验证要比较的对象的类型是否与您要比较的类相同 。 To achieve this, you should use getClass().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;
}
}
Do similar for Person
in case it should not allow comparing against subclasses of it. 如果Person
不允许与它的子类进行比较,则对Person
做类似的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.