多态性如何在以下代码中起作用

发布于 2025-01-21 17:08:24 字数 456 浏览 1 评论 0原文

为什么此代码打印字符串... null

class OverloadingTest {
            
    public void display(String ref){
        System.out.println("String..."+ref);
    }
            
    public void display(Object ref){
        System.out.println("Object..."+ref);
    }
            
    public static void main(String[] args) {
        OverloadingTest test=new OverloadingTest();
        test.display(null);
                 
    }
}

Why is this code printing String... null?

class OverloadingTest {
            
    public void display(String ref){
        System.out.println("String..."+ref);
    }
            
    public void display(Object ref){
        System.out.println("Object..."+ref);
    }
            
    public static void main(String[] args) {
        OverloadingTest test=new OverloadingTest();
        test.display(null);
                 
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

地狱即天堂 2025-01-28 17:08:24
  1. 多态性在哪里?标题说有,但是代码中没有。

  2. 如果您使用了适当的IDE或已启用警告,则会收到警告,或者根据您的警告设置,甚至是编译错误,用于行test.display(null);,告诉,,你那个电话是模棱两可的。
    然后,您必须将其施放到test.display(((字符串)null); or test.display(((object)null);

更新

eclipse的最新版本(使用Eclipse Build)将不再显示“模棱两可的方法调用”警告。在Java编译器部分中突出显示这些内容的选项。

  1. Where's the polymorphism? The title says there is, but there's none in the code.

  2. If you used a proper IDE or enabled warnings, you would get a warning, or depending on your warning settings, even a compile error, for the line test.display(null);, telling you that that call is ambiguous.
    And then you'd have to cast it to test.display((String) null); or test.display((Object) null);

Update

Recent versions of Eclipse (using Eclipse Build) will NOT show the "ambiguous method call" warning anymore. The option to highlight those is missing in the Java Compiler section.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文