java - 理解抽象类的 super 关键字

标签 java super

考虑以下类:

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并且没有找到阻止此类代码被编译的限制。他们在这里:

  1. 显然

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.

  1. 因为不可能有 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.

  1. 不是这样的。

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/

相关文章:

java - ANTLR4 AST 创建 - 如何创建 AstVistor

java - Selenium:如何使用相同的类名选择第n个按钮

python - 我如何实现具有多个 init 继承的 super() ?

python - __eq__ 在 super 对象上

java - 为什么下面的执行器服务java Thread程序没有关闭?

java - 错误 : cannot find symbol class DataBindingComponent

python - super() 与非直接父级一起使用

scala - 堆叠特征中 super 的含义取决于调用站点?

Python super() 传入 *args

java - 有没有办法从随机文件中确定图像格式?