インターフェイスメソッドのサブタイプを実装するJava

Will170393:

I Javaでジェネリッククラスとメソッド乗り越えてきたし、過去の論文でこの質問に出くわしました

ここでは、画像の説明を入力します。

私は給油方法などの質問で提案されたインターフェースとクラスを実装しようとした、およびパラメータとして車の引数を渡すことに問題は認められませんでした

電動インターフェース

public interface Motorized {

    public int getFuel();

}

Vehicleクラス

public abstract class Vehicle{

    private int fuel;

    public Vehicle(int fuel) {

        this.fuel = fuel;
    }

    public String toString(){

        return("Fuel is: " + getFuel());
    }

    public int getFuel() {

        return fuel;
    }
}

Carクラス

public class Car extends Vehicle implements Motorized {

    int seats;

    public Car(int fuel, int seats) {

        super(fuel);
        this.seats = seats;
    }

    public int getSeats() {

        return seats;
    }

    @Override
    public String toString(){

        return("Fuel is: " + getFuel() + "and the car has" + getSeats() + "seats.");
    }
}

試験方法

public class VehicleTest {

    public static Motorized refuel(Motorized v) {

        return v;
    }

    public static void main(String[] args) {

        Car car = new Car(15, 5);

        System.out.println(refuel(car));
    }
}

誰かが、問題はそれの私の実装では、この問題を反映していない理由は、この質問としてあるべきものを私に説明できますか?

リノ:

メソッドの戻り値に問題の嘘:

public static Motorized refuel(Motorized v)

あなたは何の問題がで渡していないと言いましたCar、それはcompletly有効な文です。しかし、あなたはから価値を取り戻すためにしようとしていないrefuel方法:

Car car = ...
Car refueled = refuel(car); // compiler error: Motorized is not assignable to Car!

戻り値の型はあるMotorizedが、Car extends Motorizedあなたがいることを確認することはできません、Motorized返されるインスタンスがします常にあることCarこの簡単な例を参照してください。

public static Motorized refuel(Motorized v) {
    // try to refuel
    // uh oh... the gas station exploded
    // you have to change to a motorbike which just stands around
    return new Motorbike();
}

今、あなたは多分期待するCarが、あなたが得るMotorbike、そうでもキャストが失敗します。

Car refueled = (Car) refuel(car); // ClassCastException, Motorbike is not a Car

あなたはかかわらず、ジェネリックでこれを行うことができます。

public static <M extends Motorized> M refuel(M m) {
    // refuel the motorized vehicle
    return m;
}

ガスステーションが再び爆発する場合が、その後、この方法では問題があります。それは知りませんM、実際にあります。だから、これはあなたの頭痛のために命の恩人することができます。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=208561&siteId=1