问题
I have a class Vehicle which is in package A and a class Car which is in package B and I want to use equals method and take advantage of inheritance by using super(), but I don't know how to do this.
When I try to run the file in main I get this:
Exception in thread "main" java.lang.NullPointerException
at vehicle.Vehicle.equals(Vehicle.java:97)
at car.Car.equals(Car.java:104)
at Main.main(Main.java:48)
Here is the code:
public boolean equals(Vehicle other) {
if (this.type.equals(other.type)) {
if (this.year == other.year && this.price == other.price) {
return true;
} else {
return false;
}
} else {
return false;
}
}
//equals in Car
public boolean equals(Car other) {
if (this.type.equals(other.type)) {
if (this.speed == other.speed && this.door == other.door) {
if (super.equals(other)) {
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
回答1:
equals() method as per the contract should return false when null passed as an argument:
For any non-null reference value
x,x.equals(null)should returnfalse.
Add this at the very beginning of every equals() method:
if(other == null) {
return false;
}
Secondly you have to override equals(), not overload it:
public boolean equals(Object other)
Finally you'll need instanceof and downcasting to make this all work.
And BTW this:
if (this.speed == other.speed && this.door == other.door)
{
if(super.equals(other))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
is equivalent to:
if (this.speed == other.speed && this.door == other.door)
{
return super.equals(other);
}
else
{
return false;
}
which in turns can be reduced to:
return this.speed == other.speed && this.door == other.door && super.equals(other);
来源:https://stackoverflow.com/questions/14791945/using-super-for-equals-in-a-subclass-in-a-different-package