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

查看:270
本文介绍了了解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修饰符指定只能在自己的包中访问该成员(与package-private一样),此外,另一个包中其类的子类。

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 中声明的受保护成员,但仅限于的实例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天全站免登陆