【问题标题】:Java - protected access modifierJava - 受保护的访问修饰符
【发布时间】:2013-05-26 20:32:25
【问题描述】:

我有这些课程:

package abc;

public class A {

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

    public void test() {
        publicInt = 0;
        privateInt = 0;
        protectedInt = 0;
        defaultInt = 0;
    }

}

“A”包含所有四个访问修饰符的属性。这些其他类扩展“A”或创建实例并尝试访问属性。

package de;

public class D {

    public void test() {
        E e = new E();
        e.publicInt = 0;
        e.privateInt = 0; // error, cannot access
        e.protectedInt = 0; // error, cannot access
        e.defaultInt = 0; // error, cannot access
    }

}

package de;

import abc.A;

public class E extends A {

    public void test() {
        publicInt = 0;
        privateInt = 0; // error, cannot access
        protectedInt = 0; // ok
        defaultInt = 0; // error, cannot access
    }

}

package abc;

import de.E;

public class C {

    public void test() {
        E e = new E();
        e.publicInt = 0;
        e.privateInt = 0; // error, cannot access
        e.protectedInt = 0; // ok, but why?
        e.defaultInt = 0; // error, cannot access
    }

}

一切正常,除了我不明白,为什么在 C 类中,我可以访问 e.protectedInt。

【问题讨论】:

    标签: java inheritance protected


    【解决方案1】:

    我认为代码说明将有助于更好地理解这里。

    在 E 类中添加一个受保护的成员

    public class E extends A {
        protected int protectedIntE;
        ...
    

    现在,尝试在 C 类中访问它

    e.protectedInt = 0; // ok, but why?
    e.protectedIntE = 0; // error, exactly as you expected
    

    所以,这里要注意的是,尽管您通过E 的实例访问了protectedInt,但它实际上属于A 类,并且只是通过继承被E 类继承。 E 类的实际(非继承)受保护成员仍然无法像您预期的那样访问。

    现在,由于 A 类和 C 类在同一个包中,并且受保护的访问基本上可以作为包的超集(也包括子类访问)编译器在这里没有什么可抱怨的。

    【讨论】:

      【解决方案2】:

      因为C 与A(包abc)在同一个包中,而Java 中的protected 修饰符包括在同一个包中的访问。

      【讨论】:

        【解决方案3】:

        Acces Control

        点击链接,您将进入 java 文档,解释修饰符可访问性。

        protected 类、函数等对您当前的类、包和子包可见。在类的子类中也可见。

        【讨论】:

          猜你喜欢
          • 2013-04-03
          • 2013-03-05
          • 2019-05-07
          • 2014-12-29
          • 2015-02-11
          • 1970-01-01
          • 2016-04-03
          相关资源
          最近更新 更多