5/23/2006

If You Can Learn Only One Annotation

JDK 5 (aka 1.5) introduced annotations along with 6 built-in annotations. For most developers, only 1 is really worth attention: java.lang.Override. I haven't found any need to use the other 5 build-in annotations: Deprecated, Documented, Inherited, Target, RetentionPolicy.

How to use @Override?

Use it whenever a subclass overrides a method in any of its superclasses. For example:

@Override
public boolean equals(Object other) {
throw new UnsupportedOperationException("Not yet implemented");
}
If you incorrectly override the method like @Override public boolean equals(MyType other), Javac will do you a favor by issuing an error: equals method does not override any method in its superclass.

Without the help from @Override, this buggy code will pass compilation and fail randomly at runtime. The equals method in subclass won't be invoked where you think it should be. It was overloading, not overriding equals method in superclass.

When not to use @Override?

Don't use annotations if your apps may need to support JDK 1.4 or earlier. There may be some libraries enabling annotations in pre-5 JDK, but why the extra dependecy for little gain?

Don't use @Override when only implementing a method declared in an interface.

Where to put @Override?

You don't have to place @Override in its own line. In fact, any of the following is good:
  • @Override public void foo()
  • public @Override void foo()
  • public @Override synchronized void foo()
  • public synchronized @Override void foo()