In the preceding code, the test class uses an Animal reference to invoke a method
on a Horse object. Remember, the compiler will allow only methods in class Animal
to be invoked when using a reference to an Animal.
Animal c = new Horse();
c.buck(); // Can't invoke buck();
// Animal class doesn't have that method
OCPJP 6 (91%)
David Samer wrote:Greetings there everyone.
<snip>
OK, plain polymorphism , so I take, as book states, I have to watch for reference type. Fine.
In this last example makes sense , Animal reference but Horse object, and based in the above line, our var h has Animal reference, so there when trying to invoke buck() method fails.
Based in the above,why in the first example :
b having Animal reference, yet runs Horse version of eat() method? (Like if it were overloading instead an overriding )
Thanks in advance.
Ankit Gareta wrote:Hi David,
Both the examples are correct.
In first example,
Animal b = new Horse();
Here, reference is type Animal and object is type Horse.
Overriding is the Runtime-polymorphism. so overriding take place only runtime not compile time, and method call of object b depends on reference type.
here b.eat() method calls the Animal's method compile time and at runtime due to the object is type Horse , so the method override take place and runs the Horse's object...
but in your second example,
Animal h = new Horse()
h.buck() gives compile time error , because Animal doesn't have a buck() method.
Hope that will help.
Thanks,
Ankit
Kevin Florish wrote:Hi David
With polymorphism when you declare the reference type in the declaration, it can be from a superclass of the object we are creating. The compiler has no problem with this but the power of polymorphism happens at runtime through the concept of virtual method invocation. This concept is the dynamic selection of overridden methods at runtime based on the actual object type, rather than the reference type. This only applies to overridden instance methods, everything else uses the reference type at runtime.
We can use the supertype for reference type declaration when instantiating our objects, safe in the knowledge that the JVM will use the actual object created to invoke the correct overridden methods of the subtypes at runtime.
The superclass doesn't know anything about the methods in the subclass so this only works one way, so an Animal reference type can be used as a declaration and at runtime the actual Horse object is used to get the right override.
Overloading is something totally different, it's just a different method with the same name and a different argument list.
For a fuller explanation try this lesson from my site Polymorphism
Regards Kevin
The City calls upon her steadfast protectors. Now for a tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
|