多态性如何在以下代码中起作用
为什么此代码打印字符串... 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
多态性在哪里?标题说有,但是代码中没有。
如果您使用了适当的IDE或已启用警告,则会收到警告,或者根据您的警告设置,甚至是编译错误,用于行
test.display(null);
,告诉,,你那个电话是模棱两可的。然后,您必须将其施放到
test.display(((字符串)null);
or test.display(((object)null);)
更新
eclipse的最新版本(使用Eclipse Build)将不再显示“模棱两可的方法调用”警告。在Java编译器部分中突出显示这些内容的选项。
Where's the polymorphism? The title says there is, but there's none in the code.
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);
ortest.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.