Since Java 1.5, the @Override annotation type has been provided to allow developers to specify that a method declaration is intended to override or implement a method in a supertype (super class or super interface). When a method is marked with the @Override annotation, the compiler will perform a check to ensure that the method does indeed override or implement a method in super class or super interface. This helps in preventing unintentional errors such as misspelled method name, wrongly-typed parameters or anything that does not obey overriding rules.
Let’s consider an example. The java.lang.Object class declares the equals() method as follows:
public boolean equals(Object obj) { … }
And a class Foo is attempting to override the equals() method as follows:
class Foo { public boolean equals(Foo obj) { // Foo's implemention of equals() goes here } }
This seems a perfectly legal overriding, but actually not. Rather, this is actually an overloading. Because the class Foo has the Object class as its supertype implicitly, it inherits the equals() method with a parameter of type Object:
public boolean equals(Object obj)
Whereas the Foo class’ equals() method has a parameter of type Foo:
public boolean equals(Foo obj)
So to make sure this is exactly an overriding, put the @Override annotation before the method like this:
@Override public boolean equals(Foo obj) { // Foo's implemention of equals() goes here }
When compiling this code, the compiler will issue a compile error:
method does not override or implement a method from a supertype
So we are warned that something goes wrong, we know that this is not a legal overriding. To solve the problem, change the parameter type to Object as follows:
@Override public boolean equals(Object obj) { // Foo's implemention of equals() goes here }
And the compiler will be happy.
When a method declaration is annotated the @Override annotation, the compiler will generate a compile-time error if:
Superclass:
class Foo { public void doSomething(String thing, int times) { } }
Subclass:
class Bar extends Foo { @Override public void doSomething(String thing, int times) { // do something cooler } }
Super interface:
interface Kool { void playCool(int x, int y); }
Subclass:
class Kooler implements Kool { @Override public void playCool(int x, int y) { } }
class Person { @Override public boolean equals(Object obj) { } @Override public int hashCode() { } @Override protected Person clone() { } }
This won’t compile because the clone() method is declared protected in the Object class:
interface Kool { @Override public Object clone(); }
But this will compile:
interface Boom { @Override boolean equals(Object obj); }
Other Annotations in Core Java: