【问题标题】:Couldn’t understand the output of this code? [duplicate]无法理解这段代码的输出? [复制]
【发布时间】:2013-08-10 13:17:00
【问题描述】:
     public class Test {

   public void method(String param)
   {
       System.out.println("String version");
   }

   public void method(StringBuffer param)
   {
       System.out.println("String Buffer");
   }

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

此代码结果是编译错误说“对方法的引用不明确”

    public class Test
{
    public void method1(Object param)
    {
        System.out.println("Object Version ");
    }

    public void method1(String param)
    {
        System.out.println("String Version ");
    }

    public static void main(String[] args)
    {
        Test test=new Test();
        test.method1(null);
    }
}

此代码结果为“字符串版本”

实际上我无法理解第二段代码的结果。为什么两段代码的结果不一样

【问题讨论】:

    标签: java string overloading stringbuffer


    【解决方案1】:

    在第一种情况下,

    null 是所有其他引用类型的子类型。 因此,编译器在决定调用哪个方法时发现模棱两可。

    在第二种情况下,它为null 找到更具体的对象,恰好是字符串。因此它调用method1 并打印String Version

    【讨论】:

    • 但对象也接受空值。编译器为什么选择String??
    • 字符串扩展对象,因此更具体
    • @Yasmin Java Docs 告诉编译器总是选择最具体的方法。 String 比 Object 更具体。
    • 并且作为 String 和 StringBuffer 它们都从 Object 类扩展,编译器计数器模棱两可,对吧??
    • @Yasmin:没错。编译器不知道哪个更具体,因此会抛出错误。
    猜你喜欢
    • 2020-05-14
    • 2013-08-08
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2012-10-24
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多