Why can outer Java classes access inner class private members? Why can outer Java classes access inner class private members? java java

Why can outer Java classes access inner class private members?


The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class. They are intended to be used when you have 2 requirements:

  1. Some piece of functionality in your outer class would be most clear if it was implemented in a separate class.
  2. Even though it's in a separate class, the functionality is very closely tied to way that the outer class works.

Given these requirements, inner classes have full access to their outer class. Since they're basically a member of the outer class, it makes sense that they have access to methods and attributes of the outer class -- including privates.


If you like to hide the private members of your inner class, you may define an Interface with the public members and create an anonymous inner class that implements this interface. Example bellow:

class ABC{    private interface MyInterface{         void printInt();    }    private static MyInterface mMember = new MyInterface(){        private int x=10;        public void printInt(){            System.out.println(String.valueOf(x));        }    };    public static void main(String... args){        System.out.println("Hello :: "+mMember.x); ///not allowed        mMember.printInt(); // allowed    }}


The inner class is (for purposes of access control) considered to be part of the containing class. This means full access to all privates.

The way this is implemented is using synthetic package-protected methods: The inner class will be compiled to a separate class in the same package (ABC$XYZ). The JVM does not support this level of isolation directly, so that at the bytecode-level ABC$XYZ will have package-protected methods that the outer class uses to get to the private methods/fields.