Java downcasting dilemma
- by Shades88
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.