- A
protected
member is accessible outside a package only in subclass.
- If you need to access a
protected
member variable outside package, it needs to be accessed only through inheritance.
- If it needs to be accessed using reference variable, it needs to be in same package.
Following example elaborates above.
When you modify a member variable as protected
, then that protected member variable is accessible outside package ONLY through inheritance.
Statement x.y1 = 3;
it trying to access using reference variable which is not possible outside package.
If you want to access it simply make it y1 = 3
.
Using below code should enable you to access y1
package whatever;
import somepack.A1;
class B2 extends A1 {
void h(somepack.A1 x) {
System.out.println(y1);
y1 = 3;
System.out.println(y1);
}
public static void main(String args[]){
B2 obj = new B2();
obj.h(new A1());
}
}
This will print below.
0
3
So as you can see we can directly assign value to protected member using inheritance only.
Now let us see how we can access using reference variable type i.e. without inheritance.
package somepack;
public class A1 {
protected int y1;
}
class C{
public static void main(String args[]){
A1 obj = new A1();
System.out.println(obj.y1);
}
}