• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Overloading

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 335
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Santana,

Thanks for your help!

Now I understand the behavior of JVM for this situation.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic