实例与铸造,多态性

时间:2012-11-11 12:39:10

标签: java casting instanceof

基于我的一个较老的问题Link我正在努力学习更多有关Casting和Instanceof的内容。这是基于HeadFirst书中描述的场景

所以基本上我现在有了一个新的类(Hybrid)继承自我的Vehicle类,我正在尝试做的是投射一个混合对象来显示混合所带来的额外信息。它符合,但并没有真正让我知道是什么导致错误,除了它只是在我标记的行上结束。

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());
        }
    }
}

1 个答案:

答案 0 :(得分:4)

你需要演员吗?您已经重写了displayDetails()方法以显示特定于混合的信息。所以你应该能够调用它,运行时将确定要调用的正确方法。

相关问题