Accessing outer class members from within an inner class extending the outer class itself

The method getValue() and the field value are both private. As such, they are not accessible to any other classes, including sub-classes, ie. they are not inherited.

In InnerClass#showValue()

public void showValue() {
    System.out.println(getValue());
    System.out.println(value);
}

because of the fact that those are private, getValue() and value are referring to the outer class’ members, which are accessible because you are in the same class, ie. inner classes can access outer class private members. The above calls are equivalent to

public void showValue() {
    System.out.println(TestInnerClass.this.getValue());
    System.out.println(TestInnerClass.this.value);
}

And since you’ve set value as

new TestInnerClass("Initial value")

you see "Initial value" being printed twice. There is no way to access those private members in the sub-class.


The point is: don’t make sub classes inner classes.

Leave a Comment