Require override of method to call super

前端 未结 7 2370
既然无缘
既然无缘 2020-12-17 08:11

I want that when a child class overrides a method in a parent class, the super.method() is called in that child method.

Is there any way to check this a

7条回答
  •  旧时难觅i
    2020-12-17 08:47

    Well, I can presume that the initialization in the superclass method is used elsewhere. I would set a flag in the superclass method and check it later when the initialization is needed. More specifically, let's say setupPaint() is superclass method that needs always to be called. so then we can do:

    class C {
      private boolean paintSetupDone = false;
    
      void setupPaint() { 
        paintSetupDone = true;
        ...
      }
    
      void paint() { // requires that setupPaint() of C has been called
         if (!paintSetupDone) throw RuntimeException("setup not done");
         ...
      }
    }
    

    Now if a subclass of C doesn't call the setupPaint() function, there's no way that the (private) flag will be set, and methods requiring the contractual call to the superclass setupPaint(), such as paint() will be able to check and throw that exception.

    As noted elsewhere, there is by the way no way of requiring such a contract in java.

提交回复
热议问题