如何在子类中访问超类的"protected static"变量,其中子类位于不同的包中..?

Pra*_*sad 10 java

这是同一个问题的略微详细版本.

我们无法访问子类中受保护的变量(超类),其中子类位于不同的包中.我们只能访问supeclass的继承变量.但是如果我们将修饰符更改为'protected static',那么我们也可以访问超类的变量.为什么会那样.?

这是我试图解释的代码片段.

package firstOne;

public class First {
    **protected** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10; // Here i am overriding the protected instance variable

    public static void main (String [] args){
        Second SecondObj = new Second();
        SecondObj.testit();
    }
    public void testit(){
        System.out.println("value of A in Second class is " + a);
        First b = new First();
        System.out.println("value in the First class" + b.a ); // Here compiler throws an error.
    }
}
Run Code Online (Sandbox Code Playgroud)

上述行为是预期的.但我的问题是,如果我们将超类实例变量'a'的访问修饰符更改为'protected static',那么我们也可以访问变量(超类的变量).我的意思是,

package firstOne;

public class First {
    **protected static** int a=7;
}

package secondOne;

import firstOne.*;

public class Second extends First {
    protected int a=10;

    public static void main (String [] args){
        System.out.println("value in the super class" + First.a ); //Here the protected variable of the super class can be accessed..! My question is how and why..?
        Second secondObj = new Second();
        secondObj.testit();
    }

    public void testit(){
        System.out.println("value of a in Second class is " + a);
    }

}
Run Code Online (Sandbox Code Playgroud)

上面的代码显示了输出:

超级7中的价值

test1类中x的值为10

这怎么可能...?

Rya*_*art 5

来自“检查对 Java 虚拟机中受保护成员的访问”:

\n
\n

m为在属于包p的类c中声明的成员。如果m是公共的,则任何类(其中的代码)都可以访问它。如果m是私有的,则只能由c访问。如果m具有默认访问权限,则它只能由属于p的任何类访问。

\n

如果m受到保护,事情会稍微复杂一些。首先,m可以被属于p的任何类访问,就好像它具有默认访问权限一样。此外,它可以被属于与p不同的包的c的任何子类s访问,但有以下限制:如果m不是静态的,则正在访问其成员的对象的类o必须是s或 a s的子类,写为o \xe2\x89\xa4 s(如果m是静态的,则该限制不适用:m始终可以被s访问)。

\n
\n

我在JLS 第 6.6.2.1 节中找到了该引用,它支持有关“正在访问其成员的对象必须是s或其子类...”的部分。我没有看到任何支持 static 子句的内容,但根据您自己的示例,这显然是正确的。

\n