简体   繁体   English

为什么受保护的成员被放置在不同包中的类的子类的子类访问

[英]Why protected member is accessed by subclass of subclass of a class which are placed in different packages

Why this code runs fine??为什么这段代码运行良好?

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();
    }
}

This gives output:这给出了输出:

x is 9 x 是 9

5 5

But how can subclass(Child) of subclass(C) can access protected member of class Parent.但是subclass(Child) subclass(C) subclass(Child)subclass(C) subclass(Child) subclass(C)如何访问父类的受保护成员。

In your example class Child extends C and class C extends Parent.在您的示例中,Child 类扩展了 C,C 类扩展了 Parent。 This means Child is a subclass of Parent.这意味着 Child 是 Parent 的子类。 Protected fields are visible both to all subclasses and to classes in the same package.受保护的字段对所有子类和同一包中的类都是可见的。 https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问父级子类中静态类的受保护成员 - Accessing protected member of static class in subclass of the parent 子类访问中的受保护方法,它位于不同的包中 - Protected methods in subclass access which is in different package 如何在子类中访问超类的“protected static”变量,其中子类位于不同的包中..? - How can ‘protected static’ variable of superclass be accessed in the subclass, where subclass resides in different package..? 从不同包的另一个实例的子类调用受保护的方法 - Call protected method from a subclass of another instance of different packages 子类 inheritance 与不同的包? - subclass inheritance with different packages? 受保护的为什么不能在不同的包子类中访问? - protected can't access in different package subclass why? 为什么protected对于不同的子类包中的其他类变得私有 - why protected becomes private to other classes in different package of subclass Java中哪个类不能成为子类,为什么? - Which class can not be a subclass in java and why? 在子类之外访问 Java 超类变量? - Java super class variable accessed outside of subclass? Java访问不同包中子类中的受保护成员,使用父类型的对象引用 - Java access to protected member in subclass in different package, using object reference of parent type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM