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{ // also tried to extend Car
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. As mentioned in the comment I also tried to extend Car using bike. According to some discussion here, Bike is not a car because it is extending vehicle. If I extend Car by a Bike, then it means Bike is a type of Car, still the exception remains.
Please help me understand what is going on around here.
P.s – please don’t take the whole convert car to bike, bike to car literally 😉
No, the code provided differs from the code in your example in a basic sentence:
They’re not the same. In the first example, you’re using the parent class to save the value, in the second you’re using a child class and assigning a parent value, but the object will be a child, not the parent.
Let’s see the classes composition for further explanation:
As you can see, every
String[]will be aObject, now everyCarwill be aVehicle, but aCaris not aBike. Explaining it with code