【发布时间】:2012-06-05 10:30:57
【问题描述】:
我在浏览匿名内部类时遇到以下疑问
这是我下载的 Original 代码并正在解决它(请参阅下面的代码仅针对我的问题)。
根据上面的链接,他们说我们不能在匿名内部类中重载和添加其他方法。
但是当我编译下面的代码时,虽然我无法在 Inner 类之外调用这些公共方法,但它工作正常。
起初我很惊讶为什么我不能访问 Inner 类之外的公共方法,但后来我意识到 Object 由不知道此类函数调用的“父”类引用持有。
我可以在下面的代码中进行哪些更改以调用 Inner 类之外的重载方法和新方法?
class TestAnonymous
{
public static void main(String[] args)
{
final int d = 10;
father f = new father(d);
father fAnon = new father(d){
// override method in superclass father
void method(int x){
System.out.println("Anonymous: " + x);
method("Anonymous: " + x); //This Compiles and executes fine.
newMethod(); //This Compiles and executes fine.
}
// overload method in superclass father
public void method(String str) {
System.out.println("Anonymous: " + str);
}
// adding a new method
public void newMethod() {
System.out.println("New method in Anonymous");
someOtherMethod(); //This Compiles and executes too.
}
};
//fAnon.method("New number"); // compile error
//fAnon.newMethod(); // compile error - Cannot find Symbol
}
public static final void someOtherMethod()
{
System.out.println("This is in Some other Method.");
}
} // end of ParentClass
class father
{
static int y;
father(int x){
y = x;
this.method(y);
}
void method(int x){
System.out.println("integer in inner class is: " +x);
}
}
【问题讨论】:
标签: java overloading anonymous-class