【问题标题】:Why protected member is accessed by subclass of subclass of a class which are placed in different packages为什么受保护的成员被放置在不同包中的类的子类的子类访问
【发布时间】:2017-06-04 11:53:54
【问题描述】:

为什么这段代码运行良好??

package certification;
public class Parent {
    protected int x = 9; // protected access
    protected void z(){System.out.println(5);}
}


package other;
import certification.Parent;
class C extends Parent{}
public class Child extends C {
    public void testIt() {
        System.out.println("x is " + x);
        this.z();
    }

}

import other.Child;
class Test extends Child{
    public static void main(String args[]){
        new Child().testIt();
    }
}

这给出了输出:

x 是 9

5

但是subclass(C)subclass(Child) 怎么能访问Parent 类的受保护成员。

【问题讨论】:

标签: java oop


【解决方案1】:

在您的示例中,Child 类扩展了 C,C 类扩展了 Parent。这意味着 Child 是 Parent 的子类。 受保护的字段对所有子类和同一包中的类都是可见的。 https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 1970-01-01
    • 2018-02-11
    • 2016-07-05
    • 2011-10-16
    • 2016-10-01
    • 2012-07-22
    • 2013-03-05
    相关资源
    最近更新 更多