Unexpected overloaded method compiler selection with null parameter

96 views Asked by At

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);
    }
}
2

There are 2 answers

3
Eran On

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);
0
soufrk On

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.