I have two classes Person
and Teacher
. In the Person
class I check if the two objects passed in are equal using the compareTo method. In the Teacher
class, the problem I'm working on states that I need to override the equals
method in Person. 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
. 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?
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:
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
And the implementation of Teacher#equals
doesn't meet this requirement. 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. To achieve this, you should use 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.