aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading 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 » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloading" Watch "Overloading" New topic
Author

Overloading

Richard Rex
Ranch Hand

Joined: Sep 19, 2005
Posts: 100
Hi,

While having a mock test, I encountered this question and still can't figure out what JVM does with this?

What is the output of the following program?

class Super { }
class Sub extends Super { }

public class Test {
public void foo(Sub sub) {
System.out.println("Sub");
}

public void foo(Super sup) {
System.out.println("Super");
}

public static void main(String[] args) {
new Test().foo(null);
}
}

The answer here is "Sub". I looked for an explanation for the mock test but I found no explanation.

Can somebody explain the behavior of JVM regarding this? How come it's not the method foo that takes an argument of Super is called?


"If you fail to plan, you plan to fail."<br /> <br />Chad<br />SCJP 1.4<br />SCWCD 1.4<br />SCBCD 1.3<br />SCDJWS (next)
Santana Iyer
Ranch Hand

Joined: Jun 13, 2005
Posts: 335
null can be assigned to any object or anywhere an object is expected.

foo() is overloaded, when you pass null it can be assigned to both
Super or Sub.
Now they are in inheritace hierarchy so most specific is chosen
i.e. Sub so foo(Sub s) is called

do one thing class Sub { } remove extends Super
and check now compiler error as null can be applied to both methods
and now no specific method as no inheritance or hierarchy.

hope this helps.
Richard Rex
Ranch Hand

Joined: Sep 19, 2005
Posts: 100
Hi Santana,

Thanks for your help!

Now I understand the behavior of JVM for this situation.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overloading