我有一个名为Xpto的抽象类和两个扩展它的子类,名为Person和Car。我还有一个名为Test的类,它带有 main() 和一个方法foo(),用于验证两个人或汽车(或扩展 Xpto 的类的任何对象)是否相等。因此,我在 Person 和 Car 类中重新定义了equals() 。两个人同名时相等,两辆车同名时相等。
但是,当我在 Test 类中调用 foo() 时,我总是得到“假”。我明白为什么:equals() 没有在 Xpto 抽象类中重新定义。那么......我如何在该 foo() 方法中比较两个人或汽车(或扩展 Xpto 的类的任何对象)?
总之,这是我的代码:
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);
}
}