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:
@OverrideIf you incorrectly override the method like
public boolean equals(Object other) {
throw new UnsupportedOperationException("Not yet implemented");
}
@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()