3

Say there is an class named MyOuter which consists of a simple inner class named MyInner. In trying to learn how inner classes work, I'm trying to understand whether an outer class private member variable is accessible from the inner class itself or not.

class MyOuter {
  private int x = 7;
  // inner class definition
  class MyInner {
    public void seeOuter() {
      System.out.println("Outer x is " + x);
    }
  } // close inner class definition
} // close outer class

As per my analysis, the preceding code is perfectly legal. Notice that the inner class is indeed accessing a private member of the outer class. That's fine, because the inner class is also a member of the outer class. So just as any member of the outer class (say, an instance method) can access any other member of the outer class, private or not, the inner class (also a member) can do the same.

Please advise whether my reason was correct or not.

1
  • 2
    Correct, but you can ask your compiler. Commented Feb 28, 2013 at 1:33

1 Answer 1

2

an inner class is a member of its enclosing class and has direct access to that object's methods and fields. for more information, please see Nested Classes.

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

4 Comments

Isn't it the same OP also mentioned.... "the inner class is also a member of the outer class. So just as any member of the outer class (say, an instance method) can access any other member of the outer class, private or not, the inner class—also a member—can do the same"
@Jayamohan, Right, this was just me saying yes, he's right. And then I provided some reference material. I don't see what the problem is here? Also, does the down-voter care to explain?
yeah, If "YES" is included in the reply It would have been great, thats why commented.
The access, strictly speaking, is not direct. At least, not unless a JIT compiler optimizes it. Instead, package-private accessors are synthesized in the enclosing class at compile time. The inner class uses these accessors, rather than directly accessing the fields.

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.