为什么我不能调用同名匿名类之外的方法 [英] Why can't I call a method outside of an anonymous class of the same name
问题描述
最后的代码产生编译错误:
The code at the end produces a compile error:
NotApplicable.java:7: run() in cannot be applied to (int)
run(42);
^
1 error
问题是为什么?为什么javac 认为我在调用run(),却没有找到run(int bar)?它正确地调用了 foo(int bar).为什么我必须使用 NotApplicable.this.run(42);?是bug吗?
The question is why? Why does javac think I am calling run(), and does not find run(int bar)? It correctly called foo(int bar). Why do I have to use NotApplicable.this.run(42);? Is it a bug?
public class NotApplicable {
public NotApplicable() {
new Runnable() {
public void run() {
foo(42);
run(42);
// uncomment below to fix
//NotApplicable.this.run(42);
}
};
}
private void run(int bar) {
}
public void foo(int bar) {
}
}
推荐答案
对你的代码示例行为的解释是 this
被定义为你当前最"在里面的类的.在这种情况下,您在子类 runnable 的匿名内部类中最",并且没有与 run(int)
匹配的方法.要扩大搜索范围,您可以通过声明 NotApplicable.this.run(42)
来指定要使用的 this
.
The explanation for the behavior of your code sample is that this
is defined to be the class that you are currently "most" inside of. In this case, you are "most" inside the anonymous inner class that subclasses runnable and there is no method which matches run(int)
. To broaden your search you specify which this
you want to use by stating NotApplicable.this.run(42)
.
jvm 将评估如下:
this
-> 当前正在使用方法 run()
this
-> currently executing instance of Runnable
with method run()
NotApplicable.this
-> 当前正在使用方法 run(int)
NotApplicable.this
-> currently executing instance of NotApplicable
with method run(int)
编译器将查找与方法名称匹配的第一个方法的嵌套树.–感谢 DJClayworth 的澄清
The compiler will look up the nesting tree for the first method that matches the NAME of the method. –Thanks to DJClayworth for this clarification
匿名内部类不是外部类的子类.由于这种关系,内部类和外部类都应该能够拥有一个签名完全相同的方法,并且最内层的代码块应该能够识别它想要运行的方法.
The anonymous inner class is not a subclass of the outer class. Because of this relationship, both the inner class and the outer class should be able to have a method with exactly the same signature and the innermost code block should be able to identify which method it wants to run.
public class Outer{
public Outer() {
new Runnable() {
public void printit() {
System.out.println( "Anonymous Inner" );
}
public void run() {
printit(); // prints "Anonymous Inner"
this.printit(); //prints "Anonymous Inner"
// would not be possible to execute next line without this behavior
Outer.this.printit(); //prints "Outer"
}
};
}
public void printit() {
System.out.println( "Outer" );
}
}
这篇关于为什么我不能调用同名匿名类之外的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!