简体   繁体   中英

Regarding inner classes private member variable access

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM