Jump over parent constructor to call grandparent's

后端 未结 10 1830
遥遥无期
遥遥无期 2020-12-18 22:27

The problem is this: I have an abstract class that does some work in its constructor, and a set of child classes that implement the abstract class:

class Abs         


        
10条回答
  •  一向
    一向 (楼主)
    2020-12-18 22:59

    One way I came up with:

    class AbstractClass {
         AbstractClass(){ init(); }
         protected init(){ /* useful implementation */ }
    }
    
    class ConcreteClass1 extends AbstractClass {
         ConcreteClass1(){ init(); /* useful implementation */ }
    }
    
    class CustomizedClass1 extends ConcreteClass1 {
        CustomizedCLass1(){ init(); /* useful implementation */ }
    }
    

    In this way, CustomizedClass1 gets the behavior it needs from AbstractClass without passing through ConcreteClass1 initializations.

    EDIT: Ouch, this doesn't work because the parent's constructors are implicitly called as one of the commenters pointed out, I think the easy way is to have different constructors.

提交回复
热议问题