In the below code snipped, why is "Sub" printed. Why not "Super". How is this resolved?
01. class Super { } 02. class Sub extends Super { } 03. 04. public class Test { 05. public void foo(Super sup) { 06. System.out.println("Super"); 07. } 08. 09. public void foo(Sub sub) { 10. System.out.println("Sub"); 11. } 12. 13. public static void main(String[] args) { 14. new Test().foo(null); 15. } 16. }
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
posted
0
From the Java Language Specification, 2nd Edition:
If more than one method declaration is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
The informal intuition is that one method declaration is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error.
"public void foo(Sub sub)" is more specific than "public void foo(Super sup)" because you are guaranteed that all Sub objects are Super objects, but there can be Super objects that are not Sub objects.