我在浏览匿名内部类时遇到了以下疑问
这是我下载并正在解决的原始代码(请参阅下面的代码仅用于我的问题)。
根据上面的链接,他们说我们不能在匿名内部类中重载和添加其他方法。
但是当我编译下面的内容时,它工作正常,尽管我无法在 Inner 类之外调用这些公共方法。
最初我很惊讶为什么我无法访问 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的静态类型系统冲突。从概念上讲,变量fAnon
是 father
的类型,它没有.method(String)
或.newMethod
方法。
你想要的是father
的一个普通(命名)子类:
class fatherSubclass extends father
{ /* ... */ }
你应该声明你的新变量
fatherSubclass fAnon = new fatherSubclass(d)
我可以在下面的代码中进行哪些更改,以便在内部类之外调用重载方法和新方法?
只是让它不是一个匿名类。您可以在方法中声明该类:
public static void main(String[] args) {
class Foo extends Father {
...
}
Foo foo = new Foo();
foo.method("Hello");
}
。但我可能会建议将其设置为单独的类,如有必要,可以嵌套在外部类中,或者只是一个新的顶级类。
一旦你开始想对匿名类做任何复杂的事情,通常最好把它分解成一个成熟的命名类。
您不能从匿名类外部调用"重载"和新方法。您可以在匿名班级内呼叫他们,但永远不能从外部调用他们。外界根本不知道他们。没有类或接口规范包含有关它们的信息。