gpt4 book ai didi

java - 子类中的 equals 方法

转载 作者:行者123 更新时间:2023-11-30 10:53:54 25 4
gpt4 key购买 nike

这是主类。

public class Person {
private String name;

public Person() {
name = "";
}

它的equal方法是这样的

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;
}

我将如何编写它的 equal 方法来比较两个 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;
}

最佳答案

首先:如果你测试instanceof,你不需要测试null; null 不是 instanceof 任何东西。因此,equals() for 方法可以简化为:

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()。

关于java - 子类中的 equals 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com