This week's book giveaways are in the iOS and Features new in Java 8 forums. We're giving away four copies each of Barcodes with iOS: Bringing together the digital and physical worlds and Core Java for the Impatient and have the authors on-line! See this thread and this one for details.
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".
A superclass reference can point to a subclass object.
This is how polymorphism is achieved in java.
Don't worry about it.
Read about java inheritance and polymorphism better.
One book (the book that i read) is java2 complete reference with really good examples.Please try that
To err is human,
To forgive is not company policy
Joined: Dec 30, 2009
Vijitha Kumara wrote:And Welcome to JavaRanch
Thanks Vijitha Kumara and Sagar Rohankar
Joined: Dec 30, 2009
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