views:

237

answers:

3

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 anybody has a custom java annotation that could achieve the same effect. Essentially what i want is to push for subclasses to override a method in a superclass that itself has some logic that must be run-through. I dont want to use abstract methods or interfaces, because i want some common functionality to be run in the super method, but more-or-less produce a compiler warning/error denoting that derivative classes should override a given method.

+5  A: 

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.

cletus
A: 

... and if declaraing a base class abstract is not an option you can always throw an UnsupportedOperationException

class BaseClass {
    void mustOverride() {
        throw new UnsupportedOperationException("Must implement");
    }
}

But this is not a compile-time check of course...

armandino
A: 

I'm not sure which attribute you're thinking about in .NET.

In VB you can apply the MustOverride modifier to a method, but that's just the equivalent to making the method abstract in Java. You don't need an attribute/annotation, as the concept is built into the languages. It's more than just applying metadata - there's also the crucial difference that an abstract method doesn't include any implementation itself.

If you do think there's such an attribute, please could you say which one you mean?

Jon Skeet