Why is classcastException not thrown at compile time during suppression?

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(); // line 1
        Vehicle v2 = new Vehicle();// line 2
        // compile time error. Type mis-match
        Car c0 = v1; // line 3
        // v1 has knowledge of Car due to line 1
        Car c1 = (Car) v1;//line 4
        // Runtime Exception. v2 has no knowledge of car
        Car c2 = (Car) v2;//line 5

    }
}
+4
2

Java ​​. Vehicle v2 = new Vehicle(), Java , v2 "it Vehicle Vehicle.

+3

, , v1 v2. . . , .

+3

Source: https://habr.com/ru/post/1529273/


All Articles