minal silimkar wrote:
Line below gives runtime error ClassCastException, it does not give any error or warning at compile time
B b=(B)new A();
Minal,
If we simplify your main method's content,
In line 1 we have created a reference 'a' of type A which refers to Object of type A. In line 2 we have created a reference 'b' and we are trying to DOWNCAST the reference of type A to type B. As A and B are in the same hierarchy compiler won't complain about DOWNCASTING. Now the current situation is a reference b of type B refers to object of type A. And compiler comes to know about this fact at runtime because at compile time it is still thinking that it would point to correct object type (optimistic

) . but when it comes to know about the fact that it is pointing to wrong object type it fails (crashes with broken heart). Now tell me , will below work?
What would be the output?