Video in progress
The code works even without the @Override annotation. So why is it needed?
@Override tells the compiler "this method overrides a method of a parent class or interface". If there is a mistake in the signature (the name or a parameter type), the compiler gives an error immediately; otherwise a new method quietly appears and the bug stays hidden.
📖 Answer
A classic mistake:
public class Point {
private final int x, y;
// ...
public boolean equals(Point other) { // Point, not Object!
return other != null && x == other.x && y == other.y;
}
}
This doesn't override equals(Object), it overloads it. But HashSet<Point> and list.contains(p) call equals(Object), so two equal points come out as "not equal".
With @Override in place, the compiler tells you right away: method does not override or implement a method from a supertype.
Other benefits:
- if a method is renamed in the parent class, every child gets an error, so no place is forgotten;
- someone reading the code sees at once that the method is part of an outside contract.
Always write @Override when implementing interface methods too. In many teams Checkstyle or an IDE inspection enforces this.
Sign up to mark studied questions and save your progress.