Question

Consider the example below. line 5 of main(commented) throws ClassCastException at Runtime. Line 4 is a valid cast because v1 has "knowledge" of car". In the same token, shouldn't line 5 give compile time error since it has "knowledge of v2" being a vehicle and not car and hence throw compile time error saying "hey I have no knowledge of car, I am a vehicle, you can't be cast to a car".

During compile time, Vehicle v1 = new Car(), a new Car is not created. but v1 has knowledge that it is a car correct?

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

    }
}
Was it helpful?

Solution

Java doesn't propagate information like that. As soon as you say Vehicle v2 = new Vehicle(), Java forgets any knowledge of what v2 is other than "it's Vehicle or some subtype of Vehicle.

OTHER TIPS

No, the compiler doesn't know what the actual object being referenced by v1 or v2. It only knows the reference type. The actual object comes into picture at runtime. So, the compiler wouldn't and it shouldn't give you compiler error for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top