21
votes

In Java, the inner class can access private members of enclosing class. But can the outer class access private members of inner class? This is irrespective of whether inner class is static or not. I thought this is not true but the following code seems to compile and work fine.

public class Outer {
    class Inner {
        private int i = 0;
        private Inner() {}
    }

    public static void main(String[] args) {
        Outer o = new Outer();
        Outer.Inner oi = o.new Inner();
        oi.i = 10;
    }
}
1
Looks as expected to me. Except you mean <code>oi.i = 10;</code> yes?Ben
I don't understand. The code is right here. I know the output. I know it works. I wanted to understand the reasoning behind it. Do you think this question does not deserve an answer?user236215
Can you provide example where such construction can be needed? If u want to know it's theoretically it's ok, but I've never met it before)Shell Scott

1 Answers

25
votes

Yes, that's fine. From the JLS, section 6.6.1:

Otherwise, 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 or constructor.

You can even refer to a private member of nested type X within another nested type Y so long as they share a top-level class.

At the bytecode level, I believe this is all implemented by adding synthetic package-access methods.