0

Could someone please explain how private members of a static nested class are accessible outside the class?

class Main {
    static class Inner{
        private static int calc= 10;
    }

    public static void main(String args[]){
        System.out.println("calc is "+Main.Inner.calc);
    }
}

1 Answers1

2

The inner class is just a way to cleanly separate some functionality that really belongs to the original outer class.

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. The JVM does not support this level of isolation directly, so that at the bytecode-level will have package-protected methods that the outer class uses to get to the private methods/fields.

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.

Shadi Jumaa
  • 188
  • 1
  • 11