javainner-classesouter-classes

Access inner class private vars from outer class


I am trying to access private val inside an inner class, from the outer class without creating an instance of the inner class.

Is this even possible to access private inner class values from the outer class ?

Thanks in advance.


Solution

  • If the field is static, you already can access it from the outer class even if it's private. You don't need an instance of either the inner or the outer class:

    public class Clazz {
        class Inner {
            private static final int N = 10;
        }
        public static void main(String[] args) {
            System.out.println(Inner.N);
        }
    }
    

    If the inner class field is not static, it does not exist without an instance of the inner class. You can't access something that doesn't exist.