[英]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.