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

后端 未结 4 1949
深忆病人
深忆病人 2020-12-03 15:50

In the code snippet shown below, an inner class inherits an outer class itself.

package test;

class TestInnerClass {

    private String value;

    public          


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-03 16:02

    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.

提交回复
热议问题