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
  • 2
    What kind of answer are you looking for? Because the language was designed that way? Commented Jan 16, 2021 at 9:09

1 Answer 1

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.

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

1 Comment

Thank you for clearing this doubt of mine, Shadi!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.