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.

 

Some Rules about @Override annotation:

When a method declaration is annotated the @Override annotation, the compiler will generate a compile-time error if:

 

Java @Override Annotation Examples:

 

Other Annotations in Core Java:

 

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.