Consider the example below. line 5 of main(commented out) throws ClassCastExceptionon Runtime. Line 4 is valid castbecause v1 has the “knowledge” of the car. At the same time, line 5 should not give an error compile time, since it has “knowledge v2”, which is a vehicle and not a car, and therefore throw out a compile time error, saying: “Hey, I don’t know the car, I'm a car, you can't be thrown into a car. "
It is Vehicle v1 = new Car()not created at compile time new Car. but v1 knows this car is right?
class Vehicle {
}
class Bus extends Vehicle {
}
class Car extends Vehicle {
}
public class UpcastDownCast {
public static void main(String[] args) {
Vehicle v1 = new Car();
Vehicle v2 = new Vehicle();
Car c0 = v1;
Car c1 = (Car) v1;
Car c2 = (Car) v2;
}
}