Java-抽象类,equals()和两个子类 [英] Java - abstract class, equals(), and two subclasses
问题描述
我有一个名为 Xpto 的抽象类,以及两个扩展了它的子类,名为 Person 和 Car .我还有一个名为main的 Test 类和一个方法 foo(),该方法验证两个人或汽车(或扩展Xpto的类的任何对象)是否在等于.因此,我在Person和Car类中都重新定义了 equals().两个人的名字相同,两个人的名字相同,两辆车的名字相同,则两个人的名字相等.
I have an abstract class named Xpto and two subclasses that extend it named Person and Car. I have also a class named Test with main() and a method foo() that verifies if two persons or cars (or any object of a class that extends Xpto) are equals. Thus, I redefined equals() in both Person and Car classes. Two persons are equal when they have the same name and two cars are equal when they have the same registration.
但是,当我在Test类中调用foo()时,总是得到"false".我明白为什么:在Xpto抽象类中未重新定义equals().那么...如何在该foo()方法中比较两个人或两个汽车(或扩展Xpto的类的任何对象)?
However, when I call foo() in the Test class I always get "false". I understand why: the equals() is not redefined in Xpto abstract class. So... how can I compare two persons or cars (or any object of a class that extends Xpto) in that foo() method?
总而言之,这是我的代码:
In summary, this is the code I have:
public abstract class Xpto {
}
public class Person extends Xpto{
protected String name;
public Person(String name){
this.name = name;
}
public boolean equals(Person p){
System.out.println("Person equals()?");
return this.name.compareTo(p.name) == 0 ? true : false;
}
}
public class Car extends Xpto{
protected String registration;
public Car(String registration){
this.registration = registration;
}
public boolean equals(Car car){
System.out.println("Car equals()?");
return this.registration.compareTo(car.registration) == 0 ? true : false;
}
}
public class Teste {
public static void foo(Xpto xpto1, Xpto xpto2){
if(xpto1.equals(xpto2))
System.out.println("xpto1.equals(xpto2) -> true");
else
System.out.println("xpto1.equals(xpto2) -> false");
}
public static void main(String argv[]){
Car c1 = new Car("ABC");
Car c2 = new Car("DEF");
Person p1 = new Person("Manel");
Person p2 = new Person("Manel");
foo(p1,p2);
}
}
推荐答案
正如其他人所说,您重写的方法的签名必须完全相同.覆盖方法时,为确保覆盖,请使用函数上方的 @Override
批注,因此,如果您更改了方法,则Eclipse之类的IDE会发出警告.
As the others say, the signature of the method you override must be exactly the same. When overriding methods, to make sure you are overriding, use the @Override
annotation above the function, so IDEs like Eclipse will warn you if you changed the method.
是这样的:
@Override
public boolean equals(Object obj){
...Your code here...
}
我建议也覆盖 hashCode()
,因为在将项目插入列表,集合,hastables等中以实现相等(并执行)时, hashCode()
>被使用(有时不是 equals()
!)
I would suggest to override hashCode()
as well because when inserting items into lists, sets, hastables, etc... for equality (and performande) hashCode()
is used (and sometimes equals()
is not!)
因此,您的最终代码将是:
So your final code would be:
@Override
public boolean equals(Object obj){
...Your code here...
}
@Override
public int hashCode(){
...Your code here...
}
更多信息,请参见 javadoc
这篇关于Java-抽象类,equals()和两个子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!