Can anyone explain, why can't I access protected variable in a subclass of another package?
Testp2, OtherPackage, and Protection2 classes are stored in package p2, while Protection class is stored in p1 package. System.out.println("n_pro = "+p.n_pro);
of Protection2.java shows error
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);
}
}
The stacktrace is as follows:
C:\Users\jaina_000\Desktop\learn_java>javac p2/Testp2.java .\p2\Protection2.java:9: error: n_pro has protected access in Protection System.out.println("n_pro = "+p.n_pro); // when uncommented produces err (protected access specifier) ^ .\p2\OtherPackage.java:9: error: n_pro has protected access in Protection System.out.println("n_pro = "+p.n_pro); // when uncommented prod uces err(protected access specifier) ^ 2 errors
C:\Users\jaina_000\Desktop\learn_java>