As you shown in your code, using sub class reference if I try to refer to super class using casting it will work. But code I tried gives class cast exception.
Using sub class reference that actually points to super class object, you can only call methods that have been overridden by the subclass.
In other words methods specific to sub class can not be invoked in this way.
In fact the dog reference points to Animal object at run time, if Animal class doesn't have makeSound(), it fails.
Using sub class reference that actually points to super class object, you can only call methods that have been overridden by the subclass. In other words methods specific to sub class can not be invoked in this way.
If you check code I originally posted, I am invoking overriden method in main, which gives runtime error ClassCastException.
It is going to fail if the sub class reference refers to super class object at run time, giving you ClassCastException.
Compiler forgives us doing down casting, thinking the reference variable may refer to sub class object.
Line below gives runtime error ClassCastException, it does not give any error or warning at compile time
B b=(B)new A();
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?