23

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;
    }
}
4
  • 1
    Looks as expected to me. Except you mean <code>oi.i = 10;</code> yes? Commented Feb 8, 2010 at 12:54
  • 1
    Duplicate: stackoverflow.com/questions/1801718/… Commented Feb 8, 2010 at 13:29
  • 3
    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? Commented Feb 10, 2010 at 14:02
  • 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) Commented Jun 2, 2016 at 14:22

1 Answer 1

27

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.