Sobes.tech
Middle

How do you access a field of an outer class from an inner class?

sobes.tech AI

Answer from AI

It is possible to access a field of the outer class from an inner class using a qualified this.

public class OuterClass {

    private int outerField = 10;

    public class InnerClass {

        public void accessOuterField() {
            // Access to the outer class's field through OuterClass.this
            int value = OuterClass.this.outerField; 
            System.out.println("Value of outerField: " + value);
        }
    }

    public static void main(String[] args) {
        OuterClass outer = new OuterClass();
        OuterClass.InnerClass inner = outer.new InnerClass();
        inner.accessOuterField(); 
    }
}

In the case of static nested classes, direct access to non-static fields of the outer class is not possible, since a static class is not associated with a specific instance of the outer class. Access is only possible to static fields of the outer class, or if an instance of the outer class is passed to the nested class.

How do you access a field of an outer class from an… - sobes.tech