任何人都可以解释一下,为什么我不能在另一个包的子类中访问受保护的变量?
Testp2,OtherPackage和Protection2类存储在包p2中,而Protection类存储在p1包中。 Protection2.java的System.out.println("n_pro = "+p.n_pro);
显示错误
package p2;
public class Testp2
{
public static void main(String a[])
{
// instantiating the classes of p1 package...
Protection2 ob = new Protection2();
OtherPackage ob2 = new OtherPackage();
}
}
public class OtherPackage
{
OtherPackage()
{
p1.Protection p = new p1.Protection();
System.out.println("Inside SamePackage constructor.");
// System.out.println(" n = "+p.n);
// System.out.println("n_pri = "+p.n_pri);
System.out.println("n_pro = "+p.n_pro);
System.out.println("n_pub = "+ p.n_pub);
}
}
public class Protection2 extends p1.Protection{
Protection2(){
p1.Protection p = new p1.Protection();
System.out.println("Inside SamePackage constructor.");
// System.out.println(" n = "+p.n);
// System.out.println("n_pri = "+p.n_pri);
// System.out.println("n_pro = "+p.n_pro); // when uncommented produces err(protected access specifier)
System.out.println("n_pub = "+p.n_pub);
}
}
package p1;
public class Protection{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection(){
System.out.println("Inside base constructor.");
System.out.println(" n = "+n);
System.out.println("n_pri = "+n_pri);
System.out.println("n_pro = "+n_pro);
System.out.println("n_pub = "+n_pub);
}
}
堆栈跟踪如下:
C:\ Users \ jaina_000 \ Desktop \ learn_java> javac p2 / Testp2.java 。\ p2 \ Protection2.java:9:error:n_pro在Protection中具有受保护的访问权限 System.out.println(" n_pro =" + p.n_pro); //当取消注释时会产生错误 (受保护的访问说明符) ^ 。\ p2 \ OtherPackage.java:9:error:n_pro在Protection中具有受保护的访问权限 System.out.println(" n_pro =" + p.n_pro); //当没有注释时 urs err(受保护的访问说明符) ^ 2个错误
C:\用户\ jaina_000 \桌面\ learn_java>