java 区分 method isaccessible_java – polymorph歧义区分如何工作?

这个问题实际上是关于解决模糊的重载,而不是关于运行时多态性(因为选择要在调用时完成调用的重载方法).

方法解析是一件复杂的事情,在这种情况下,代码是否完全编译取决于所涉及的类型.在很多情况下代码都会编译.请参阅下面的代码(请注意String实现CharSequence):

public class MyClass {

MyClass(CharSequence charSeq) {

System.out.println("CharSequence");

}

MyClass(String s) {

System.out.println("String");

}

public static void main(String[] args) {

new MyClass(null); // prints "String"

new MyClass(""); // prints "String"

new MyClass((CharSequence) null); // prints "CharSequence"

new MyClass((CharSequence) ""); // prints "CharSequence"

}

}

请注意,如果没有强制转换,则选择String重载.这与JLS中指定的完全相同:

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.

String是一个CharSequence,但并非所有CharSequence都是一个String.因此,String比CharSequence更具体,因此在上面的示例中选择了String重载.

值得注意的是,这个确切的问题(实质上)出现在精彩的Java Puzzlers(强烈推荐)中,特别是益智46:令人困惑的构造函数的案例

Java’s overload resolution process operates in two phases. The first phase selects all the methods or constructors that are accessible and applicable. The second phase selects the most specific of the methods or constructors selected in the first phase. One method or constructor is less specific than another if it can accept any parameters passed to the other

The key to understanding this puzzle is that the test for which method or constructor is most specific does not use the actual parameters: the parameters appearing in the invocation. They are used only to determine which overloadings are applicable. Once the compiler determines which overloadings are applicable and accessible, it selects the most specific overloading, using only the formal parameters: the parameters appearing in the declaration.

我将结束有效Java第2版的引用,第41项:明智地使用重载:

The rules that determine which overloading is selected are extremely complex. They take up thirty-three pages in the language specification, and few programmers understand all of their subtleties.

毋庸置疑,这本书也值得推荐.

也可以看看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值