1

基于我的一个较旧的问题Link我正在努力了解有关 Casting 和 Instanceof 的更多信息。这是基于 HeadFirst 书中描述的场景

所以基本上我现在有了一个继承自我的 Vehicle 类的新类(Hybrid),我想做的是投射一个 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 回答