1

私のリンクの古い質問に基づいて、私はCastingとInstanceofについてもっと学ぶことに取り組んでいます。これは、HeadFirstの本で説明されているシナリオに基づいています

つまり、基本的には、Vehicleクラスから継承する新しいクラス(Hybrid)を取得しました。これは、ハイブリッドオブジェクトをキャストして、ハイブリッドであることに伴う追加情報を表示することです。準拠していますが、マークした行で終了することを除いて、エラーの原因はわかりません。

public class ShowroomDriver {
    public static void main(String[] args) {
    Showroom cars = new Showroom("Cars");
    Hybrid hybrid1 = new Hybrid("Toyota Prius", "Focus", "John Smith", "TOTAP453453987346283",
            getCalendar(2,3,1998), getCalendar(24,2,2012),
            "Right Hand",//Hybrid Only Info Edit: Forgot to commentout 
            true,
            'C',
            650, 82.0); //Cost & (Hybrid MPG)

    cars.addVechicle(hybrid1);
    cars.getVechicles();

ハイブリッドクラス

import java.util.Calendar;

public class Hybrid extends Vehicle{
    private double consumption;
    private String drive;

    public Hybrid(String Manufacture, String Model, String CustomerName, String Vin, 
            Calendar DateManufactured, Calendar Datesold, String Drive,
            boolean HasbeenSold,
            char TaxBand,
            double Cost, double Consumption){

        super(Manufacture, Model, CustomerName, Vin, DateManufactured, Datesold,
                HasbeenSold,
                TaxBand,
                Cost);
        this.consumption = Consumption;
        this.drive = Drive;
    }

    public Double getConsumption() { return this.consumption; }
    public String getDrive() { return this.drive; }
}

新しい車両方式

public void displayDetails(){
    for(int i = 0; i <cars.theVehicles.size(); i++){
        if(this.cars.theVehicles.get(i) instanceof Hybrid){//Error here
            Hybrid thehybrids = (Hybrid)this.cars.theVehicles.get(i);
            System.out.println("Consumption: " + thehybrids.getConsumption()+ "\n" +
                    "Drive: " + thehybrids.getDrive());
        }
    }
}
4

1 に答える 1

4

キャストする必要がありますか?ハイブリッド固有の情報を表示するには、displayDetails()メソッドを既にオーバーライドしています。したがって、これを呼び出すことができるはずであり、ランタイムが呼び出す正しいメソッドを決定します。

于 2012-11-11T12:43:06.937 に答える