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 adds 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 is 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.
