Using super() for equals() in a subclass in a different package

。_饼干妹妹 提交于 2019-12-12 03:50:10

问题


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 return false.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!