Accessing private member via subclass
I thought I understood Java's access control rules pretty well, but
this case puzzles me.
public abstract class Super
private int i;
void method(Sub s)
s.i = 2; // (*)
public class Sub extends Super
Consider the starred line. The field "i" is private to Super and is
being accessed by Super, which seems to me to fit within JLS 6.6.1:
if the member or constructor is declared private, then access
is permitted if and only if it occurs within the body of the top
level class (?7.6) that encloses the declaration of the member
However, trying to compile these classes leads to:
Super.java:7: i has private access in Super
s.i = 2;
in both 1.4.2_09 and 1.6.0_06.
Obviously, the error can be removed by changing the line to
((Super)s).i = 2;
And, just as obviously, the error doesn't actually prevent
encapsulation from being broken. For what it's worth, similar (in
fact, almost identical) C# code compiles with no problems.
Any thoughts about this?