Jump over parent constructor to call grandparent's

后端 未结 10 1844
遥遥无期
遥遥无期 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条回答
  •  旧时难觅i
    2020-12-18 22:52

    Is CustomizedData1 a subclass of ConcreteData1? If so, then I would suggest having a (possibly protected) constructor for ConcreteClass1 that takes in a ConcreteData1 to use instead of fetching its own during initialization. This way, CustomizedClass1 can fetch its CustomizedData1 and pass it to its call to super. Unfortunately this may be tricky or fairly impossible if you can't fetch the data prior to some internal init.

    
    class ConcreteClass1 extends AbstractClass {
         ConcreteClass1(){
              this(...fetch data as before...);
         }
         ConcreteClass1(ConcreteData1 data){
              myData = data;
              ...
         }
    }
    class CustomizedClass1 extends ConcreteClass1 {
         CustomizedCLass1(){
              super(new CustomizedData1(...));
              ... 
         }
    }
    

    But then CustomizedClass1 probably needs a reference to the data as a CustomizedData1 not merely a ConcreteData1. It could just typecast its inherited ConcreteData1 all the time, but that seems yucky. But if it stores its own reference to the data, then there is a need to keep the references in sync if they're not final.

提交回复
热议问题