考虑以下类:
public abstract class AbstractClass {
public abstract String m();
public AbstractClass get(){
return new AbstractClass() {
@Override
public String m() {
return "Anonymous " + super.m(); //1, Compile-time erro
}
};
}
}
目前还不清楚为什么这样使用 super
是被禁止的。在//1
处,出现如下错误
Cannot directly invoke the abstract method m() for the type AbstractClass
所以,我咨询了JLS 15.11.2并且没有找到阻止此类代码被编译的限制。他们在这里:
- 显然
It is a compile-time error if the forms using the keyword super appear in the declaration of class Object, since Object has no superclass.
- 因为不可能有
AbstractClass
的实例,而只有它的一个具体 子类,所以在我看来,以下内容也是有效的:
The forms using the keyword super are valid only in an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If they appear anywhere else, a compile-time error occurs.
- 不是这样的。
It is a compile-time error if the current class is not an inner class of class T or T itself.
当然,我可以使用 AbstractClass.this.m()
,但这不是我要问的。
最佳答案
super 关键字在这里不起作用,因为 AbstractClass.m()
已被声明为抽象的,因此在内部类的父级上没有合适的实现。请记住,内部类不会扩展外部类(即使它属于同一类型),而是包含对其的引用。
然而,当从调用外部类的内部类工作时(我相信你打算在这里做的)然后使用以下语法 AbstractClass.this.m()
。
以下将按预期编译和工作。
public abstract class AbstractClass {
public abstract String m();
public AbstractClass get(){
return new AbstractClass() {
@Override
public String m() {
return "Anonymous " + AbstractClass.this.m();
}
};
}
}
关于java - 理解抽象类的 super 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33012167/