File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading

 
Richard Rex
Ranch Hand
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Santana Iyer
Ranch Hand
Posts: 335
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 100
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic