I have the following 2 methods overloaded in a class :
public class Test{
public static void main(String []args) throws ParseException{
Test t = new Test();
t.testMethod(null);
}
public void testMethod(Object o){
System.out.println("Object");
}
public void testMethod(String s){
System.out.println("String");
}
}
When I invoke the method testMethod
it print "String".
When I add one more overloaded method :
public void testMethod(StringBuilder sb){
System.out.println("String");
}
It throws me compiler error : The method testMethod is ambigous for type Test
..
All this happens when I invoke the method with null
My questions are :
Method resolution works by selecting the most specific method that is applicable for the given arguments. In your first case, String
is more "specific" than Object
(since it is a subclass of Object
) and so the String
method is chosen.
When you add another method that takes a StringBuilder
, both that and the String
method are equally "specific" (they are both direct subclasses of Object
), so there is an ambiguity as to which should be chosen, hence the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With