问题描述
我注意到,如果我有两个同名方法,当我用SomeOtherObject
调用方法时,第一个方法接受SomeObject
,第二个方法接受扩展SomeObject
的对象,它会自动使用仅接受SomeObject
.如果我将SomeOtherObject
强制转换为SomeObject
,则即使对象是SomeOtherObject
的实例,也会使用接受SomeObject
的方法.这意味着在编译时选择了该方法.为什么?
I noticed that if I have two methods with the same name, the first one accepts SomeObject
and the second one accepts an object extending SomeObject
when I call the method with SomeOtherObject
, it automatically uses the one that only accepts SomeObject
. If I cast SomeOtherObject
to SomeObject
, the method that accepts SomeObject
is used, even if the object is an instanceof SomeOtherObject
. This means the method is selected when compiling. Why?
推荐答案
这就是Java中方法重载解析的工作方式:该方法是在编译时选择的.
That's how method overload resolution in Java works: the method is selected at compile time.
有关所有丑陋的详细信息,请参见 Java语言规范§ 15.12.
For all of the ugly details, see the Java Language Specification §15.12.
这篇关于Java中两个具有相同名称的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!