Melky
Melky

Reputation: 167

Instanceof and Casting, Polymorphism

Based on a older question of mine Link I'm working on learning more about Casting and Instanceof. That is based upon a scenario described in a HeadFirst book

So basically I've now got a new class(Hybrid) that inherits from my Vehicle class what i'm trying to do is cast a Hybrid Object to display the extra information that comes with being a hybrid. It complies but doesn't really give me any idea what is causing the error except it just ends on the line i've marked.

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

Hybrid Class

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

New Vehicle Method

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

Upvotes: 1

Views: 517

Answers (1)

Brian Agnew
Brian Agnew

Reputation: 272257

Do you need to cast ? You've already overridden the displayDetails() method to display hybrid-specific info. So you should just be able to call this and the runtime will determine the correct method to call.

Upvotes: 4

Related Questions