-1

I have following program with method overloading. Can someone please explain me the output of following program.

public class test {

    public void display(Object obj)
    {
        System.out.println("object method");
        System.out.println(obj);
    }
    public void display(String str)
    {
        System.out.println("String method");
        System.out.println(str);
    }

    public static void main(String[] args) {
        test t=new test();
        t.display(null);
    }

}
i23
  • 508
  • 2
  • 12
user2085714
  • 139
  • 1
  • 2
  • 8
  • If you wish to test small bits of code like this, try [compilejava.net](http://compilejava.net) and it correctly shows it uses the String method – phflack Oct 26 '15 at 13:32
  • 1
    This answers why display(String) is getting called rather than display(Object) if that's what you're asking: http://stackoverflow.com/questions/2608394/how-is-ambiguity-in-selecting-from-overloaded-methods-resolved-in-java – JJF Oct 26 '15 at 13:32

1 Answers1

2

The least generic (most specific) constructor will be called. So, public void display(String str) will be called and hence String method followed by null will be printed

Object class is at the top of the hierarchy of classes. String, StringBuilder, Exception etc are at 1 level below Object. IOException is one level below Exception. So, if you have 3 methods one taking Object, another Exception and another IOException, the method with IOException will be called, since it is at the lowest level in the class hierarchy (least generic).

Try putting 2 classes which are at the same level and see what happens :)

TheLostMind
  • 35,966
  • 12
  • 68
  • 104