This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "overridden method output" Watch "overridden method output" New topic
Author

overridden method output

Vasim Patel
Ranch Hand

Joined: Apr 29, 2004
Posts: 87
Hi,

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
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: http://aspose.com/file-tools
 
subject: overridden method output