[英]Parent class accessing protected members of subclasses Java
I have the following code which I think is not totally explained by Oracle's tutorials. 我有以下代码,我认为Oracle的教程并没有完全解释。
package visibilidad;
import otropaquete.*;
public class ejemplo2 extends Test {
protected int prot = 4;
}
package otropaquete;
import visibilidad.*;
public class Test {
public void metodopublico() {
ejemplo2 a = new ejemplo2();
System.out.println(a.prot);
Hija b = new Hija();
System.out.println(b.prot);
}
}
class Hija extends Test {
protected int prot = 3;
}
Basically, what I'm trying to do is to access a protected member of subclasses from the parent class. 基本上,我要做的是从父类访问受保护的子类成员。 The funny thing is that this gives a compile time error when the subclass is defined in another package and it runs perfectly if the subclass is defined in the same class.
有趣的是,当子类在另一个包中定义时,这会产生编译时错误,如果在同一个类中定义了子类,则它会完美运行。
I would like to know if this behaviour is considered in the standard or not. 我想知道是否在标准中考虑了这种行为。
The docs are very explicit: protected
fields are accessible in the Class, Package and Subclass level. 文档非常明确:
protected
字段可在Class,Package和Subclass级别访问。 Since the parent is neither a subclass nor inside the same package - the field is not accessible and you're getting a compilation error. 由于父既不是子类也不在同一个包内 - 该字段不可访问,并且您收到编译错误。
The access-levels table from Oracle docs: Oracle文档中的访问级别表:
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
In Java
there are 4 different access modifiers: 在
Java
有4种不同的访问修饰符:
(No Modifier) - Visible to the package.
(无修饰符) - 包装可见。
(private) - Visible to the class only.
(私人) - 仅对班级可见。
(public) - Visible to the world.
(公开) - 向世界展示。
(protected) - Visible to the package and all subclasses.
(受保护) - 对包和所有子类可见。
Using the protected
modifier means only other classes
of that package and subclasses
can access the field/method. 使用
protected
修饰符意味着只有该包和subclasses
classes
的其他classes
才能访问该字段/方法。 In your case the class from the same package works fine and the one from a different package throws compile time error which is exactly what is supposed to happen. 在您的情况下,来自同一个包的类工作正常,而来自不同包的类会抛出编译时错误,这正是应该发生的错误。
The protected
modifier allows access from the same package as well. protected
修饰符也允许从同一个包访问。 See the documentation . 请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.