It is not a bug. It is a tricky case of access control. When you are saying
you are accessing a private instance variable inside a method which is perfectly legal.
But when you say
you are obtaining a refernce of type A and trying a access its instance variable which in effect is private to B (because they are in different packages). It is equivalent to saying
Remember that protected members are accessible only through inheritance outside the package. What you are trying to do is to access them directly.
The code works fine when both classes are in same package as you can access a protected member outside the class within the same package.
Hope this helps.
Joined: Dec 06, 2003
Thank you very much, Satish. My explanation (which repeats yours but seems clearer to me) is: If getThis returns an object of type A, one can't know whether this object secretly is of type B. B only has access if this is the case.
-> Changing getThis to the following removes the error:
If B had access to the protected fields of any A it could modify protected fields of other subclasses of A.