gpt4 book ai didi

java - 理解Java的protected修饰符

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:46 24 4
gpt4 key购买 nike

我在 package1 中有一个名为 A 的类,在 package2 中有另一个名为 C 的类。 C 类扩展了 A 类。

A 有一个实例变量,其声明如下:

protected int protectedInt = 1;

这是A类的代码

package package1;

public class A {

public int publicInt = 1;
private int privateInt = 1;
int defaultInt = 1;
protected int protectedInt = 1;

}

这是 C 类的代码:

package package2;
import package1.A;

public class C extends A{

public void go(){
//remember the import statement
A a = new A();
System.out.println(a.publicInt);
System.out.println(a.protectedInt);

}
}

Eclipse 在 C.go() 中的最后一行下划线,并表示“A.protectedInt”不可见。鉴于 Oracle 文档所述,这似乎与“protected”关键字的定义相冲突:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

这是怎么回事?

最佳答案

What's going on here?

您误解了 protected 的含义。您可以从 C 中访问 A 中声明的 protected 成员,但仅限于 C 的实例或 C 的子类。请参阅section 6.6.2 of the JLS有关 protected 访问的详细信息。特别是:

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

In addition, if Id denotes an instance field or instance method, then:

  • [...]

  • If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S.

(强调我的。)

所以这个代码就可以了:

C c = new C();
System.out.println(c.publicInt);
System.out.println(c.protectedInt);

关于java - 理解Java的protected修饰符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603817/

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