发布于2023-05-17 20:23 阅读(1229) 评论(0) 点赞(21) 收藏(1)
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
e.g. 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.
作者:黑洞官方问答小能手
链接:http://www.javaheidong.com/blog/article/673596/9dbd3ce5d6b4128a1782/
来源:java黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 java黑洞网 All Rights Reserved 版权所有,并保留所有权利。京ICP备18063182号-2
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!