We must remember the factors behind protected access:
1-You make a class member variable and methods protected if you want to make it accessible outside the package too BUT only through inheritance. Protected means package + kids. Kids are the subclasses that may be outside the package of the class in which the protected member is defined.
2-Outside the package, you can�t access protected member of a class using the reference of the class in which it is defined. This statement needs good clarification. OK! So let�s give you a good example to get insight of the concept
package certification;
public class A {
protected int x=10;
}
package
scjp;
import certification.A;
public class B extends A{
void display(){
//First way to access protected member x of class A in package certification
System.out.println(�x = � + x);
//Second way to access protected member x of class A in package certification
B b1 = new B();
System.out.println(�x = � + b1.x);
//and what can�t be done, means restricted
A a1 = new A();
System.out.println(�x = � + A1.x);//compiler error
}
}
/* MORE CLARIFICATION*/
package scjp;
public class C extends B {
void display() {
//First way to access the protected member of class B
System.out.println(�x = � + x);
//Second way to access the protected member of class B
C c1 = new C();
System.out.println(�x = � + c1.x);
//What causes compilation error, or restricted to do
B b1 = new B();
System.out.println(�x = � + b1.x); //NO, compiler error
A a1 = new A();
System.out.println(�x = � + a1.x);//NO, compiler error
}
}
Conclusion: Protected member of a class in other package can only be accessed by the subclass in another package directly as if it would member of the same class; in other words without using dot �.�operator, or using the reference of self, that extends the parent class. You see that, class C can�t acccess the member x using reference of the class B but inside class B the protected member x of class A of package certification is easily accessed. It directly means that for the extending class the protected member remains protected for the next inheriting classes but private for others which are not subclasses. Here private for others means, if there is another class in package �scjp� that is standalone means does not extend the class B or so. If it tries to access the protected (inherited from A) member x, it fails to access because it is private to outside world except the inheriting classes.
[ February 28, 2007: Message edited by: Chandra Bhatt ]
[ February 28, 2007: Message edited by: Chandra Bhatt ]