0

I am very surprised why output is very much different from what I am expecting , I have two overloaded methods, one having one String and the other an Object as parameter, while calling this method with null parameter, output is just printing "String" and not calling method having object as parameter.

Why does Java selects the method having String as parameter, how java determines which overloaded method to call ?

class TestingClass {
    public void test(String s) {
        System.out.println("String");
    }

    public void test(Object o) {
        System.out.println("Object");
    }

    public static void main(String[] args) {
        TestingClass q = new TestingClass();
        q.test(null);
    }
}
soufrk
  • 825
  • 1
  • 10
  • 24
Jitendra Prajapati
  • 1,002
  • 1
  • 10
  • 33
  • Repeat it after me. Overriding happens only in derived classes and that too only if the method parameters are the same. The return type is allowed to be covariant. – MS Srikkanth Apr 20 '16 at 06:24
  • A more detailed text explaining what Eran has said. [Look for Denis answer](http://stackoverflow.com/questions/1572322/overloaded-method-selection-based-on-the-parameters-real-type) – pvxe Apr 20 '16 at 06:29

2 Answers2

2

There is no overriding in this code, only method overloading. When the compiler has to choose which of the two test methods to execute (since null can be passed to both), it chooses the one with the more specific argument type - test(String s) - String is more specific than Object since it is a sub-class of Object.

The other method can be called using :

q.test((Object) null);
Eran
  • 387,369
  • 54
  • 702
  • 768
0

Without adding a possible new answer, let me suggest you to extend your code like following,

public class Overload {

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

    public void test(String s) {
        System.out.println("String");
    }

    public void test(Object o) {
        System.out.println("Object");
    }

    public void test(Integer s) {
        System.out.println("Integer");
    }

}

Comment out any one of Object or Integer version any see it for yourself. The answer being already provided by others.

soufrk
  • 825
  • 1
  • 10
  • 24