Why can outer Java classes access inner class private members?

I observed that Outer classes can access inner classes private instance variables. How is this possible? Here is a sample code demonstrating the same:

class ABC{
    class XYZ{
        private int x=10;
    }

    public static void main(String... args){
        ABC.XYZ xx = new ABC().new XYZ();
        System.out.println("Hello :: "+xx.x); ///Why is this allowed??
    }
}

Why is this behavior allowed?


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:

  • Some piece of functionality in your outer class would be most clear if it was implemented in a separate class.
  • 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.


    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.


    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 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
        }
    }
    
    链接地址: http://www.djcxy.com/p/92000.html

    上一篇: 静态嵌套类可以完全访问私有外部类成员?

    下一篇: 为什么外部Java类可以访问内部类私有成员?