Java中两个具有相同名称的方法 [英] Two methods with the same name in java

查看:527
本文介绍了Java中两个具有相同名称的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,如果我有两个同名方法,当我用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.

有关所有丑陋的详细信息,请参见

For all of the ugly details, see the Java Language Specification §15.12.

这篇关于Java中两个具有相同名称的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆