不能够访问受保护的字段或方法在子调用
问题描述:
我的程序如下:不能够访问受保护的字段或方法在子调用
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.
,你将不得不作出成员内部(或公共)。
为什么你在包之间有继承?你应该重新考虑你的项目结构。 – Guy