这是主要课程。
public class Person {
private String name;
public Person() {
name = "";
}
它的方法是这个
public boolean equals(Object otherObject) {
boolean isEqual = false;
if(otherObject != null && otherObject instanceof Person) {
Person otherPerson = (Person) otherObject;
if(this.name.equals(otherPerson.name))
isEqual = true;
}
return isEqual;
}
我有一个扩展Person类的子类。
public class Student extends Person {
private int studentNumber;
public Student() {
super();
studentNumber = 0;
}
我将如何编写其相等的方法来比较两个类型为Student的对象,并将比较这两个变量。姓名和学生编号。 到目前为止,我有类似于Person类。
public boolean equals(Object otherObject) {
boolean isEqual = false;
if(otherObject != null && otherObject instanceof Student) {
Student otherPerson = (Student) otherObject;
if(this.studentnumber.equals(otherPerson.studentnumber))
isEqual = true;
}
return isEqual;
}
答案 0 :(得分:1)
首先:如果测试instanceof,则无需测试null; null不是任何实例。因此,方法的equals()可以简化为:
public boolean equals(final Object obj)
{
if (!(o instanceOf Person))
return false;
final Person other = (Person) obj;
return name.equals(other.name);
}
这意味着在您的Student课程中,您可以编写如下的equals()方法:
public boolean equals(final Object obj)
{
if (!super.equals(obj))
return false;
if (!(obj instanceof Student))
return false;
return studentnumber == other.studentnumber;
}
注意:不要忘记hashCode()。
答案 1 :(得分:0)
您可以使用super.equals()。我已经使用studentNumber比较更正了一些错误。
public boolean equals(Object otherObject) {
boolean isEqual = false;
if (otherObject != null && otherObject instanceof Student) {
Student otherPerson = (Student) otherObject;
if (super.equals(otherObject) && this.studentNumber == otherPerson.studentNumber) {
isEqual = true;
}
}
return isEqual;
}