Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

The short answer is no.

The longer answer is the following. Inner class is just a regular class that has "magic" reference to instance of its outer class that can be accessible via OuterClass.this. Creating of instance of outer class does not create instance of inner class automatically. This means that you cannot by definition access members of inner class from outer class without creating instance of inner class unless inner class itself and its members are static.

Indeed you can create one instance of outer class and 10 instances of corresponding inner class. How can you access member of inner class without creating its instance?

BTW the general advice: avoid creating inner classes unless you really need them.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top