4

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

    }
}
Mik378
  • 21,881
  • 15
  • 82
  • 180
brain storm
  • 30,124
  • 69
  • 225
  • 393
  • possible duplicate of [Downcasting/Upcasting error at compile time & runtime?](http://stackoverflow.com/questions/14180861/downcasting-upcasting-error-at-compile-time-runtime) – Luiggi Mendoza Feb 27 '14 at 18:57

2 Answers2

3

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.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 1
    Additionally, that's the point where IDE's have their strengths - static code analysis where you (OP) would surely get the probably erroneous code marked. – Smutje Feb 27 '14 at 18:57
  • 1
    @Smutje Perhaps. But that will depend upon which particular code analysis tool you're using. Moreover, the rules should be configurable. – Rohit Jain Feb 27 '14 at 18:59
  • I thought of/used IntelliJ and Eclipse Checkstyle so far. – Smutje Feb 27 '14 at 19:00