Java downcasting dilemma

Posted by Shades88 on Stack Overflow See other posts from Stack Overflow or by Shades88
Published on 2012-09-03T21:17:39Z Indexed on 2012/09/03 21:38 UTC
Read the original article Hit count: 228

Filed under:

please have a look at this code here.

class Vehicle {
    public void printSound() {
        System.out.print("vehicle");
    }
}

class Car extends Vehicle {
    public void printSound() {
        System.out.print("car");
    }
}

class Bike extends Vehicle{
    public void printSound() {
        System.out.print("bike");
    }
}

public class Test {
    public static void main(String[] args) {
        Vehicle v = new Car();
        Bike b = (Bike)v;
        v.printSound();
        b.printSound();

        Object myObj = new String[]{"one", "two", "three"};
        for (String s : (String[])myObj) System.out.print(s + ".");


    }
}

Executing this code will give ClassCastException saying inheritance.Car cannot be cast to inheritance.Bike.

Now look at the line Object myObj = new String[]{"one", "two", "three"};. This line is same as Vehicle v = new Car(); right? In both lines we are assigning sub class object to super class reference variable. But downcasting String[]myObj is allowed but (Bike)v is not.

Please help me understand what is going on around here.

© Stack Overflow or respective owner

Related posts about java