0

パッケージ A にあるクラス Vehicle とパッケージ B にあるクラス Car があり、equals メソッドを使用して、super() を使用して継承を利用したいのですが、これを行う方法がわかりません。

メインでファイルを実行しようとすると、次のようになります。

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

null 以外の参照値の場合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 に答える