Imagine a class Cottage extending Building and the code
Building building = new Building();
Cottage cottage = (Cottage)building;
Now, it totally makes sense that Building cannot be casted to Cottage considering the nature of java’s inheritance, but what doesn’t make sense (to me) is that this compiles. Why does it compile and then throw a runtime ClassCastException?
Isn’t it obvious that building is a reference to a Building object before actually running the program?
Being such a general question, I know I am getting a possible duplicate for this one 🙂 but I couldn’t find an answer to WHY DOES IT COMPILE question 🙂
EDIT2 I accepted a great answer here (let alone the discussion below it 🙂 ), but I still find the accepted answer in Java casting resulting in run-time error instead of compilation error the most interesting…
EDIT I edited IllegalCastException and put the correct ClassCastException
That’s because, compiler does not know what object does your reference
Buildingis referring to.So, in the below case, where you have a base class reference, pointing to sub class object: –
It would work perfectly fine. So, it’s completely a runtime decision, as to whether it is a valid cast or not. Hence, compiler won’t throw error for that.
No. Absolutely not. The type of object being referenced, is not known till runtime. Always remember that, Compiler always checks the reference type. Actual object type is checked at runtime.
This concept is known as Polymorphism, where you can have the same reference type to point to objects of various subtypes. You can google it, and would get lots of resources to read.