Jay Frizzle Jay Frizzle - 7 months ago 6
Java Question

Can I force the explicit use of @Override?

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).

Answer

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.