When you invoke the method "callme()" on a "Animal" reference, method from the Dog object is called because by casting you are just change the reference to type "Animal" though the actual object being an instance of "Dog". Actually you don't need an explicit cast as "Animal" is the super class of "Dog", it is perfectly valid to have "Animal" reference refers to "Dog" object (this is called Polymorphism). Since you have overriden the method "callme()" defined in "Animal" within the "Dog" class, method from the "Dog" class is invoked at runtime.
Anu Kota wrote:
I was expecting "In callme of Animal". What am I missing?
For such problem, I follow my rule of thumb, like
Whenever a reference is used to call a method, then method belongs the class of that object gets called. Here "a" is of type "Animal" but it points to object of "Dog".
By casting, either up or down, I am changing the reference type only. That effects which methods can be called. If I upcast, methods in the superclass that can be inherited only can be called. If I downcast, methods that are specific to subclass can also be called. But which version of the overridden method gets called depends on the actual instance (polymorphism).
Dog d = new Dog();
((Animal)d).callme(); //Compiles, this invokes callme from Dog class.
((Animal)d).callme2(); //Compilation error
Animal a = new Dog();
a.callme(); //Compiles, this invokes callme from Dog class.
a.callme2(); //compilation error - thats why downcasting is needed
((Dog)a).callme2(); //Complies, invokes callme2 from Dog