@MustOverride annotation?

后端 未结 7 985
悲&欢浪女
悲&欢浪女 2021-02-12 22:40

In .NET, one can specify a \"mustoverride\" attribute to a method in a particular superclass to ensure that subclasses override that particular method. I was wondering whether

7条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 23:08

    Ignoring abstract methods, there is no such facility in Java. Perhaps its possible to create a compile-time annotation to force that behaviour (and I'm not convinced it is) but that's it.

    The real kicker is "override a method in a superclass that itself has some logic that must be run through". If you override a method, the superclass's method won't be called unless you explicitly call it.

    In these sort of situations I've tended to do something like:

    abstract public class Worker implements Runnable {
      @Override
      public final void run() {
        beforeWork();
        doWork();
        afterWork();
      }
    
      protected void beforeWork() { }
      protected void afterWork() { }
      abstract protected void doWork();
    }
    

    to force a particular logic structure over an interface's method. You could use this, for example, to count invocations without having to worry about whether the user calls super.run(), etc.

提交回复
热议问题