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

后端 未结 4 1946
深忆病人
深忆病人 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:10

    The other answers have explained well why you are getting the results you see (you have two instances of TestInnerClass and are accessing the first), however there is actually a way to access the private members of TestInnerClass in its subclass - the keyword super.

    If you replace your showValue method with this:

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

    You will get the output that you expected.

    I would also suggest that if you decide to do this you make InnerClass a static inner class because it no longer needs a reference to an instance of its outer class.

提交回复
热议问题