理解java的protected修饰符 [英] Understanding java's protected modifier

查看:35
本文介绍了理解java的protected修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class called A in package1 and another class called C in package2. Class C extends class A.

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

A has an instance variable which is declared like this:

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"关键字的定义相冲突.

Eclipse underlines the last line in C.go() and says "A.protectedInt" is not visible. It seems that this conflicts with the definition of the "protected" keyword, given in the oracle documentation.

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.

这是怎么回事?

推荐答案

这是怎么回事?

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

You've misunderstood the meaning of protected. You can access the protected members declared in A from within C, but only for instances of C or subclasses of C. See section 6.6.2 of the JLS for details of protected access. In particular:

设 C 为声明受保护成员的类.只允许在 C 的子类 S 的主体内访问.

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.

另外,如果Id表示实例字段或实例方法,则:

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

  • [...]

  • [...]

如果访问是通过字段访问表达式 E.Id,其中 E 是主表达式,或通过方法调用表达式 E.Id(. . .),其中 E 是主表达式,则当且仅当 E 的类型为 S 或 S 的子类时才允许访问.

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的protected修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆