Search code examples
javaclassnestedprivatemember

Java - private inner class public member


how does the access level modifier change the behavior of a member inside an inner private class? I have this code

class Main {
    private static class Inner {
        private static int a = 1;
    }
    public static void main(String[] args) {
        System.out.print(Inner.a);
    }
}

I can access the attribute "a" from the outer class either it's access level is public or private (and this is already weird for me). The question is: if the attribute were "public static int", what were the difference (considering that the Inner class is private so inaccessible from the extern of the "Main" class)?

To recap

  • The attribute is private: I can access it from Main but not from outside Main (because Inner is private)
  • The attribute is public: I can still access it from Main but not from outside Main (because Inner is private)

I can see no difference


Solution

  • Inner is private, it can be accessed only from within Main. Even if a is public, but Inner is private and cannot be accessed from a particular place, attribute of a would be irrelevant.

    class Main {
        private static class Inner {
            public static int a = 1;
        }
        public static void main(String[] args) {
            System.out.print(Inner.a);
        }
    }
    

    When you run ,

    1
    

    Whenever Inner is static in the same class,(Main), Inner (and all its members) are always accessible from anywhere in the Main class. It is private outside of Main Class. If I were to access

    Main main = new Main();
    main.Inner; // Compilation Failure. Inner is not accessible
    // Technically I would never do new Main(), but to illustrate I am doing so.
    

    Or a more sensible example of the same

    class Main {
        public static void main(String[] args) {
            System.out.print(SomeClass.Inner);
        }
    }
    
    class SomeClass{
        private static class Inner {
            public static int a = 1;
        }
    
    }
    

    To illustrate the difference of making a private or public, consider the following two examples

    class Main {
        public static void main(String[] args) {
            System.out.print(SomeClass.Inner.a);
        }
    }
    
    class SomeClass{
        public static class Inner {
            private static int a = 1;  // If a is private, it produces an error above
          //public static int a = 1; // This would not be an error
        }
    }
    

    So in your particular case, as long as it is in same class Main, it is irrelevant, but if it is outside as next example, it would matter.