java - JLS 8 关于关键字 super 和 protected 成员

标签 java super jls

在 JLS 8 15.11.2-1 (第505页),我不明白他们的意思:

Note that super.x is not specified in terms of a cast, due to difficulties around access to protected members of the superclass.

有什么帮助吗?

最佳答案

考虑一下:

public class T2 {
    protected int x = 2;
}

/* in a different package */
public class T3 extends T2 {
    int x = 3;
    void test() {
        System.out.println(this.x); // prints 3
        System.out.println(super.x); // prints 2

        T2 this_as_t2 = (T2)this;
        System.out.println(this_as_t2.x); // Error: Can't access protected member x of class T2

        System.out.println(((T2)this).x); // Same error as above
    }
}

如果 super.x 等同于 ((T2)this).x,那么您将无法使用 super.x 引用 T2 中的 x 字段。

所以规范没有说它们是等价的(因为它们并不总是相同)。但是,在某些情况下它们仍然是等效的 - 例如,如果两个类位于同一个包中,或者字段是 public

关于java - JLS 8 关于关键字 super 和 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29596601/

相关文章:

java - Android Studio 0.8.2 URI 有一个权限组件

java - 如何解析一行的前6个字符串

java - java中的 "qualified this"构造是什么意思?

java - MySQL InnoDB 在等待表级锁时挂起

java - AudioClip 不起作用,但它应该

inheritance - 在 Promise : 'super' keyword unexpected here? 中调用 super() 方法

java - 重构、使用 super 和定义

python - 在派生类中调用 super() 时,可以传入 self.__class__ 吗?

java - JLS中f1() + f2()*f3()表达式的执行顺序和运算符优先级

Java浅拷贝和深拷贝JLS