![](/img/trans.png)
[英]Inner classes with method names and different signatures than the outer class
[英]Java compiler prohibit the creation in the inner class method with same name as in the outer class if the signatures are different
为什么此代码有效:
class Parent {
private void methodA(String a){
System.out.println(a);
}
class Inner {
void test(int a){
methodA("1");
}
}
}
但是此代码不起作用(我只是将方法添加到具有相同名称和另一个签名的内部类中):
class Parent {
private void methodA(String a){
System.out.println(a);
}
class Inner {
private void methodA(int a){
System.out.println(a);
}
void test(int a){
methodA("1");
}
}
}
我不问如何使其工作。 我想说明为什么第二个选项不起作用? 我想要一个解释,而不是解决方案。
它不起作用,因为您更改了名称methodA
的含义。
由于一种称为methodA
存在于你所调用调用方法的类的主体methodA
,编译器不看周围的范围。
语言规范的特定部分为15.12.1节 (重点为我):
如果表单是MethodName,即只是一个标识符,则:
...
如果存在一个封闭的类型声明,该方法是该方法的成员,则让T为最里面的这种类型声明 。 搜索的类或接口是T。
您仍然可以通过以下方式调用父方法:
Parent.this.methodA("1");
当编译器开始扫描代码时,它首先查找最近的作用域可用性。 如果找不到,则只会进入更高的范围。
在您的情况下,编译器将在Inner
类中找到方法methodA
。 因此,它将不会寻找Parent
类中可用的方法。
仍然,如果您要强制编译器查找Parent
类方法,则必须使用以下代码。
Parent.this.methodA("1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.