views:

234

answers:

2

I have the following code :

public class Main {
     public void method(Object o)
     {
           System.out.println("Object Version");
     }
     public void method(String s)
     {
          System.out.println("String Version");
     }
     public static void main(String args[])
     {
           Main question = new Main();
           question.method(null);//1
     }
}

why is the result is "String Version" ? and why there is a compiler error if the first method takes a StringBuffer object ?
Another case : if the first method takes a StringBuffer object and I write question.method("word");the result will be "String Version" . Why ? why there is no compiler error ?

+21  A: 

The JAVA spec says that in cases like this, the most specific function will be called. Since String is a sub type of Object - the second method will be called. If you change Object to StringBuffer - there is no specific method since StringBuffer is not a sub type of String and vice versa. In this case the compiler does not know which method to call - hence the error.

duduamar
+1  A: 

When looking at the other case :

package com.snamellit;

public class Main {
    public void method(Object o) {
        System.out.println("Object Version");
    }

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

    public static void main(String args[]) {
        Main question = new Main();
        question.method("word");
    }
}

If the first method tqkes a StringBuffer and the second a String, there is no confusion possible as "word" is a String and not a StringBuffer.

In Java the identity of a function/method is dependent on 3 things : the name, the type pf the parameters (aka the argument signature) and the classloader. Since both types have a different argument signature the compiler can easily choose the right one and does not raise an error.

Peter Tillemans
But it _does_ generate an error: could you elaborate, Peter?
Tomislav Nakic-Alfirevic
thanks Peter.I thought that a compiler error should happen since "word" is a valid StringBuffer value.
M.H
No, it is a String, not a StringBuffer. StringBuffers are the mutable cousin of Strings, which are immutable and hence a great model for literal strings. A wise man said : "When in doubt, Try it out" : System.out.println("word".getClass().getName()) will print java.lang.String.
Peter Tillemans