Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloading and passing null [duplicate]

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 :

  1. Why it prints String and not Object?
  2. Why is there compilation error on adding third method?
like image 680
Abubakkar Avatar asked Sep 30 '22 07:09

Abubakkar


1 Answers

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.

like image 109
arshajii Avatar answered Oct 03 '22 00:10

arshajii