Java 无法访问子调用中的受保护字段或方法
我的计划如下:Java 无法访问子调用中的受保护字段或方法,java,Java,我的计划如下: package pack1; public class Parent { int i=0; protected j =1; public k = 2; } package pack2; import pack1.Parent; public class Child extends Parent { public static void main (String args[]) { Child c1 = new Child(); c1.j = 100;
package pack1;
public class Parent {
int i=0;
protected j =1;
public k = 2;
}
package pack2;
import pack1.Parent;
public class Child extends Parent {
public static void main (String args[]) {
Child c1 = new Child();
c1.j = 100; // This is working fine
Parent c2 = new Child();
c2.j=200; // Compilation error
}
}
我的问题是:为什么我们不能用“c2”访问父类中的受保护成员。一个无法反驳的答案是“因为规范这么说”:
您必须将成员设置为内部(或公共)。为什么在包之间有继承?你应该重新考虑你的项目结构。
A protected member of a base class is accessible in a derived class only if the access occurs through the derived class type.