0

我有一个位于包 A 中的类 Vehicle 和一个位于包 B 中的类 Car,我想使用 equals 方法并通过使用 super() 来利用继承,但我不知道该怎么做。

当我尝试在 main 中运行文件时,我得到了这个:

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)

这是代码:

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;
    }
}
4

1 回答 1

2

equals()当作为参数传递时,按照合同的方法应该返回:falsenull

对于任何非空引用值xx.equals(null)应该返回false

在每个equals()方法的最开始添加:

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

其次,您必须覆盖equals(),而不是重载它:

public boolean equals(Object other)

最后,您需要instanceof向下转换才能使这一切正常工作。

顺便说一句:

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

相当于:

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

反过来又可以简化为:

return this.speed == other.speed && this.door == other.door && super.equals(other);
于 2013-02-09T21:47:35.813 回答