I faced this doubt while appearing for the Whizlabs Mock Test (Demo Version) .
What is the result of Compiling and running the following program ?
The correct answer is : SuperSuperBase
Now my doubt is while he invocation of the following statement :
For object b1 the reference type is SuperBase and the actual object is Base. Now the polymorphic method invocation rule says that at run time the actual object method is invoked , which is Base version of print() in this case. But still its invoking the SuperBase version.
Can anyone please help me out to clarify the concept behind this ?
No it's not an override at all! All three method are overloaded since the signature of them are different. When compiler see this, it produce the codes specify method binding at compile time and not at runtime. So doesn’t matter what you pass a an argument to the Superbase.print() method, it always called once you have a reference type of Superbase.
Once again, Overriding is happening when the signature of the override method and the overridden method would be exactly the same.
Joined: Feb 05, 2009
Does that means that even if I pass a subclass object to the overriding method ...it becomes overload ?
But what about the following invocation ?
Base c1=new Derrived();
In this case the Derrived version print() is invoked.
This is overloading not overriding, and polymorphism does not apply to overloading. So the method of the reference type will be called
c1 is of type Base, even though it refers to a subclass obj. Since the subclass's print() is not an overriding version of the superclass, so the print() of the ref type will be called:
print() of Base class accept argument of type Base or any subclasses of type Base. Since Derived is subclass of Base, then this code will print "Base"
Maybe you misunderstand with the covariant return in which the return type of the overriding method can be the subclass of that of the superclass.
Here are the rules for the overriding method:
- must have the same argument list.
- must have the same return type (except the covariant return)
- may have a less restrictive access modifier.
- must not have a more restrictive access modifier.
- must not throw new or broader checked exceptions.
- may throw fewer or narrower checked exceptions, or any unchecked exceptions.
- may not throw any exceptions at all.
Hope this helps!
SCJP 6 - SCWCD in progress...
Joined: Feb 05, 2009
Thanks for your reply Shin. Yes I was getting confused with the method arguments. Each of them are subclasses of the superclass version method arguments. Now its clear to me. Thanks