3

How does null work in this code, why doesn't it print object?

class Test1{
    public void doStuff(Object o){
    System.out.println("In Object");
}

    public void doStuff(String o){
        System.out.println("In String");
    }
}

public class TTest {
    public static void  main(String args[]){    
        Test1 t = new Test1();
        t.doStuff(null);
    }
}

Output:

In String

Niklas Wulff
  • 3,497
  • 2
  • 22
  • 43
sunil shetty
  • 75
  • 1
  • 8
  • well, you are not printing the object that you are sending to the metohd. You are printing the same string everytime toStuff is called. If you change the code in doStuff to System.out.println(o); you will print the string object, which will be null and throw a nullpointerexception – John Snow Apr 12 '13 at 10:34
  • When doStuff is called because doStuff is overloaded, JVM looks for method taking more specific parameters. In this case, it is doStuff(String o) but you are not printing it. – IndoKnight Apr 12 '13 at 10:36

2 Answers2

6

Java will always try to use the most specific version of a method.

Since the call

t.doStuff(null);  

is applicable to both methods

t.doStuff(Object o)
t.doStuff(String o)

Java will choose the most specific method description, which is

t.doStuff(String o)
Keppil
  • 45,603
  • 8
  • 97
  • 119
1

As String is a subclass of Object, Java will try and use the class furthest down in the hierarchy that is applicable. null is able to be interpreted as either here, therefore the String method is used.

Quetzalcoatl
  • 3,037
  • 2
  • 18
  • 27