13

I am facing an issue in my program and I made it clear with a small code snippet below. Can anyone explain why this is happening?

class ObjectnullTest {

    public void printToOut(String string) {

        System.out.println("I am null string");
    }


    public void printToOut(Object object)

        System.out.println("I am  null object");
    }



class Test {

    public static void main(String args[]) {

        ObjectnullTest a = new ObjectnullTest();
        a.printToOut(null);

    }
}

This always prints I am null string .

I want to know the reason so that I can modify the code .

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Many others, see [http://stackoverflow.com/search?q=%5Bjava%5D+overloading+null](http://stackoverflow.com/search?q=%5Bjava%5D+overloading+null) – jlordo Feb 23 '13 at 23:08
  • Sorry for the same criterion question ,unable to find with proper key terms . – Suresh Atta Feb 23 '13 at 23:11

3 Answers3

14

It's because In case of method Overloading

The most specific method is choosen at compile time.

As 'java.lang.String' is a more specific type than 'java.lang.Object'. In your case the method which takes 'String' as a parameter is choosen.

Its clearly documented in JLS:

The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the types of the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.

There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run-time to perform the method dispatch.

Community
  • 1
  • 1
PermGenError
  • 45,977
  • 8
  • 87
  • 106
5

I agree with the existing comment about selection of the most specific method. You can force your null to be treated as an Object reference, eliminating use of the String argument method, by casting it:

a.printToOut((Object)null);
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
4

please see section 15.12.2.5 of jls that gives detail regarding how it is chosen

The most specific method is choosen at compile time

LINK TO THE JLS 15.12.2.5

recursion
  • 354
  • 6
  • 11