How does Java inheritance work when inner classes are involved

前端 未结 3 510
闹比i
闹比i 2021-01-04 09:56

I am having trouble understanding how inheritance works in Java when inner classes are present. I\'m currently working on something where a child class needs to slightly ch

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-04 10:40

    Variable are not "overriden" as methods are.

    In your call, you expected x to be the Child's one but it isn't because x is a variable, not a method.

    But pay attention: Your reference type is ParentClass so obj.x points to the ParentClass's InnerClass attribute even though the real instance behind parentClass is a ChildClass!

    In order to display your expected sentence, you have to change the type reference to ChildClass:

    public static void main(String[] args) {
          ChildClass obj = (new InnerClassTest()).new ChildClass();
          obj.x.speak();
    }
    

    To better understand the concept, try to define a method in both ParentClass and ChildClass classes:

    public InnerClass getInnerClass(){
      return x;
    }  
    

    and make x private.

    so that "override concept" applies.

    Your final call would be in this case:

    ParentClass obj = (new InnerClassTest()).new ChildClass();
    obj.getInnerClass().speak();
    

    To alter the behavior of the inner classes, think of Template method pattern or better: Strategy pattern (since more respectful of DIP)

提交回复
热议问题