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

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

    In the above case there are 2 different relations between TestInnerClass and InnerClass.

    But there is a little twist in story.. there are two objects! and the problem is that we are putting "Another Value" into different object! and printing the value from the old one..

    First Object:

    public static void main(String[] args) {
        new TestInnerClass("Initial value").callShowValue();
    }
    

    Above method in Test Class creates an instance of TestInnerClass with "Initial value"

    second Object:

    public void callShowValue() {
        new InnerClass("Another value").showValue();
    }
    

    Since the InnerClass is extending the TestInnerClass another new Instance of TestInnerClass is created with "Another Value". But we are printing the value from old object not the second one.

提交回复
热议问题