Middle
How to access the outer class's field from a nested class?
sobes.tech AI
Answer from AI
Access to a non-static nested class (inner class) field of the outer class is done directly by the field name.
Access to a static nested class (static nested class) field of the outer class is only possible through a reference to an instance of the outer class, since the static nested class does not have an implicit connection to an instance of the outer class.
// Outer class
class Outer {
private int outerField = 10;
// Non-static nested class
class Inner {
void accessOuterField() {
// Direct access to the outer class field
System.out.println("From Inner class: " + outerField);
}
}
// Static nested class
static class StaticNested {
// Does not have direct access to outerField
void accessOuterField(Outer outerInstance) {
// Access through a reference to an outer class object
System.out.println("From StaticNested class: " + outerInstance.outerField);
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.accessOuterField(); // Output: From Inner class: 10
Outer.StaticNested staticNested = new Outer.StaticNested();
staticNested.accessOuterField(outer); // Output: From StaticNested class: 10
}
}
To access an explicit outer class field when, for example, a nested class has a field with the same name, you can use the syntax Outer.this.fieldName.
class Outer {
private int field = 10;
class Inner {
private int field = 20;
void accessFields() {
// Access to the nested class's field
System.out.println("Inner field: " + field);
// Access to the outer class's field
System.out.println("Outer field: " + Outer.this.field);
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.accessFields();
// Output:
// Inner field: 20
// Outer field: 10
}
}