Overridable methods need special care
Modernize old code
@Override
annotation
was added in JDK 1.5.
It functions more or less as a new method modifier.
Its presence indicates to the compiler that the annotated method must override an existing supertype method,
either from an interface, or an abstract base class.
(When it was first introduced in
JDK 1.5, @Override
was only applicable to methods defined
in a superclass, and not in a supertype.
That is, it originally applied to overriding methods in a base class, but not to implementing
methods defined in an interface. This was changed in JDK 7, and now @Override
can be applied to both.)
The most common use case for @Override
is with
Object
methods:
@Override public String toString(){...} @Override public boolean equals(Object){...} @Override public int hashCode(){...}The main reason
@Override
was created was to deal with simple (but nasty) typographical errors.
For example, a method mistakenly declared as
public int hashcode(){...}is in fact not an override - the method name has all lower case letters, so it doesn't exactly match the name of the
hashCode()
method.
It will however compile perfectly well.
Such an error is easy to make, and difficult to catch, which is a dangerous combination.
Using the @Override
annotation prevents you from making such errors.
You should be in the habit of using @Override
whenever you override a superclass method, or
implement an interface method.