Search code examples
javastringobjectstringbuffer

OverLoading : Ambigutiy while the parameters are primitive but not while it is Reference type


public class Test {

public static void main(String[] args) throws ClassNotFoundException {


    new Test().f("dfffg");   // it is running perfectly
    new Test().f(1, 1);      // it is giving ambiguity
}

public void f(int a,long b){
    System.out.println("in int and long");
}

public void f(long a,int b){
    System.out.println("in long and int");
}

public void f(String s) {
    System.out.println("in String");

}


public void f(StringBuffer o) {
    System.out.println("in String bufer");

}

public void f(Object o){
    System.out.println("in object");
}
}

when i execute this new Test().f("dfffg"); it is running perfectly although we have overload method with StringBuffer and Object as parameter

while f(1,1) giving ambiguity, which I can understand.


Solution

  • new Test().f("dfffg") matches the signatures of both public void f(String s) and public void f(Object o). When you are passing an object parameter, the method having the most specific argument type is chosen: in this case public void f(String s). String is more specific than Object since String is a sub-class of Object.

    public void f(StringBuffer o) is not relevant in this example, since a StringBuffer is not a super-class of String, so you can't pass a String to a method that expects a StringBuffer.