1. Overview
In this quick tutorial, we’ll have a look at how to use the @Override annotation.
2. @Override Annotation
In a subclass, we can override or overload instance methods. Overriding indicates that the subclass is replacing inherited behavior. Overloading is when a subclass is adding new behavior.
Sometimes, we’ll overload by accident when we actually intended to override. It’s easy to make this mistake in Java:
public class Machine {
public boolean equals(Machine obj) {
return true;
}
@Test
public void whenTwoDifferentMachines_thenReturnTrue() {
Object first = new Machine();
Object second = new Machine();
assertTrue(first.equals(second));
}
}
Surprisingly, the test above fails. This is because this equals method is overloading Object#equals, not overriding it.
We can use the @Override annotation on inherited methods to protect us from this mistake.
In this example, we can add the @Override annotation above the equals method:
@Override
public boolean equals(Machine obj) {
return true;
}
At this point, the compiler will raise an error, informing us that we aren’t overriding equals like we think.
Then, we can correct our mistake:
@Override
public boolean equals(Object obj) {
return true;
}
Because of how easy it’s to accidentally overload, it’s a common recommendation to use the @Override annotation on all inherited methods.
3. Conclusion
In this guide, we saw how the @Override annotation works in Java.
The full source code for the examples can be found over on GitHub.