6

Is there a way to force the use of @Override annotation?

Just to clarify, I'm not asking "how do I force a subclass to implement a method" (like this):

public abstract class BaseClass {
    public abstract void foo();
}

I'm asking about this scenario specifically:

public class AnnotatedSubclass extends BaseClass {
    @Override
    public void foo() {
        System.out.println("I have @Override.");
    }
}

public class NonAnnotatedSubclass extends BaseClass {
    public void foo() {
        System.out.println("I do not have @Override.");
    }
}

Note that both compile, even though NonAnnotatedSubclass doesn't have an explicit @Override annotation. Is there a way to make the compiler throw an error/warning in the case of NonAnnotatedSubclass?

I ask, because sometimes when I extend classes I accidentally override parent methods because they have names similar to ones I would create (like .paint() in Swing).

Community
  • 1
  • 1
touch my body
  • 1,634
  • 22
  • 36
  • 1
    Your IDE can tell you when this happens and auto fix all the method which could have `@Override` but don't. – Peter Lawrey Apr 17 '16 at 20:32
  • 1
    "'m not referring to abstract methods" Oh but you should be, if it overrides a method in `BaseClass`. – Andy Turner Apr 17 '16 at 20:32
  • 1
    [Google's errorprone](http://errorprone.info/bugpattern/MissingOverride) has a check for this to require them at compile time. – Andy Turner Apr 17 '16 at 20:33
  • you should use certain static analysis tool and try to create your rules for overrided methods. Never tried to do that, though. – Benas Apr 17 '16 at 20:34
  • I think the simple rule to follow is always use @override each time you intend to override a method. Check this stack overflow question for using static analysis tools for enforcing "@override" & thereby prevent unintentional overrides: http://stackoverflow.com/questions/5794382/how-to-enforce-usage-of-the-override-annotation – MSameer Apr 17 '16 at 21:21

1 Answers1

5

The Java compiler does not explicitly force the use of @Override annotation. To do so would break backwards compatibility with pre-Java5 code.

However, static analysis tools can enforce exactly the kind of thing you want. I mostly use checkstyle to enforce use of @Override. It has an explicit rule for use of @Override and it can be integrated into all the standard Java build tools - Maven, Gradle, etc.

sisyphus
  • 6,174
  • 1
  • 25
  • 35