gpt4 book ai didi

java - 如何在子类中访问父类(super class)的 ‘protected static’ 变量,子类位于不同的包中..?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:01:15 25 4
gpt4 key购买 nike

这是同一问题的稍微详细的版本。

我们不能在子类中访问(父类(super class)的) protected 变量,子类在不同的包中。我们只能访问父类(super class)的继承变量。但是,如果我们将修饰符更改为“protected static”,那么我们也可以访问父类(super class)的变量。为什么会这样?

这是我试图解释的相同代码片段。

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.
}
}

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

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);
}

}

上面的代码显示了输出:

父类(super class) 7 中的值

test1 类中 x 的值为 10

这怎么可能……?

最佳答案

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

Let m be a member declared in a class c that belongs to a package p. If m is public, it can be accessed by (code in) any class. If m is private, it can be accessed only by c. If m has default access, it can be accessed only by any class that belongs to p.

If m is protected, things are slightly more complicated. First, m can be accessedby any class belonging to p, as if it had default access. In addition, it can be accessed by any subclass s of c that belongs to a package different from p, with the following restriction: if m is not static, then the class o of the object whose member is being accessed must be s or a subclass of s, written os (if m is static, the restriction does not apply: m can be always accessed by s).

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

关于java - 如何在子类中访问父类(super class)的 ‘protected static’ 变量,子类位于不同的包中..?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17267576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com