Ok. I have these two classes:
class A{
private static A myA = new A();
protected void a()
{
//some stuff
}
protected void test(){
myA.a(); //Hello I see you
}
}
class B extends A{
private static A myA = new A();
public void test()
{
myA.a(); //Eclipse error: Oopse a() is not visible.
}
}
I have defined the class A and a sub-class B. Inside A like we all know, I can create an instance of a and have access to everything including protected method a().
B is a sub-class of A and thus have access to protected members. But if I create an instance of A inside B, and then try to access method a() from that instance, eclipse complains that protected method is not visible.
Why is that? Is't that both class A and B are considered the same type for protected members?
Now if I change class b to:
class B extends A{
private static B myA = new B();/*I kept the name as myA to show the point*/
public void test()
{
myA.a(); //Hello, I see you now
}
}
I changed the type of myA to B, inside B. Now B is able to access the protected method a() from the myA instance. While I expected B to be able to access all protected methods of instances of A and don't see it as a violation of encapsulation.