The @Override
annotation in Java is a built-in marker annotation used to indicate that a method is intended to override a method in a superclass or implement an abstract method from an interface.
This annotation helps the compiler catch errors during compilation when the method doesn’t actually override anything (due to typo, wrong signature, etc.)
Purpose of @Override
- To improve readability and clarity that a method is overridden.
- To catch bugs during compile-time (e.g., if method signature mismatches).
- To ensure correct inheritance behavior in object-oriented programming.
Simple Program Demonstrating @Override
class Shape { void draw() { System.out.println("Drawing a shape"); } } class Circle extends Shape { @Override void draw() { System.out.println("Drawing a circle"); } } class Square extends Shape { @Override void draw() { System.out.println("Drawing a square"); } } public class OverrideSimpleDemo { public static void main(String[] args) { Shape s1 = new Circle(); Shape s2 = new Square(); s1.draw(); // Output: Drawing a circle s2.draw(); // Output: Drawing a square } }
Drawing a circle
Drawing a square
The @Override
annotation is a compiler-level safeguard that helps Java developers prevent accidental errors when extending classes or implementing interfaces. While optional, it is highly recommended in any object-oriented Java project for clarity, correctness, and maintainability.