File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes overridden method output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "overridden method output" Watch "overridden method output" New topic

overridden method output

Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87

In the below code snipped, why is "Sub" printed. Why not "Super". How is this resolved?

01. class Super { }
02. class Sub extends Super { }
04. public class Test {
05. public void foo(Super sup) {
06. System.out.println("Super");
07. }
09. public void foo(Sub sub) {
10. System.out.println("Sub");
11. }
13. public static void main(String[] args) {
14. new Test().foo(null);
15. }
16. }
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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.

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: overridden method output
It's not a secret anymore!