How is an overloaded method chosen when a paramete

2019-01-01 03:53发布

I came across this question in a quiz,

public class MoneyCalc {

   public void method(Object o) {
      System.out.println("Object Verion");
   }

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

   public static void main(String args[]) {
      MoneyCalc question = new MoneyCalc();
      question.method(null);
   }
}

The output of this program is "String Version". But I was not able to understand why passing a null to an overloaded method chose the string version. Is null a String variable pointing to nothing ?

However when the code is changed to,

public class MoneyCalc {

   public void method(StringBuffer sb) {
      System.out.println("StringBuffer Verion");
   }

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

   public static void main(String args[]) {
      MoneyCalc question = new MoneyCalc();
      question.method(null);
   }
}

it gives a compile error saying "The method method(StringBuffer) is ambiguous for the type MoneyCalc"

7条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 04:45

You can assign a string to a null value so it is valid and the order for java and most programming languages is fit to the closest type and then to object.

查看更多
登录 后发表回答