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

I have a Vehicle class that is in package A and a Car class that is in package B and I want to use the equals method and use inheritance with super (), but I don't know how to do it.

When I try to run the file basically, 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;
    }
}

      

0


source to share


1 answer


equals()

by contract should return false

when null

passed as an argument:

For any non-zero reference value x

, x.equals(null)

must return false

.

Add this to the beginning of each method equals()

:

if(other == null) {
  return false;
}

      

Second, you should override equals()

, not overload it:

public boolean equals(Object other)

      

Finally, you also need instanceof

downcasting for this to 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;
}

      

equivalent to:

if (this.speed == other.speed && this.door == other.door)
{
    return super.equals(other);
}
else
{
    return false;
}

      

which in turn boils down to:

return this.speed == other.speed && this.door == other.door && super.equals(other);

      

+2


source







All Articles