The @Override annotation is used to indicate that a method is intended to override a method from a superclass or implement a method from an interface. Although it is optional, it helps the compiler verify the correctness of the overriding method and prevents common programming mistakes.
Key Points: • @Override informs the compiler that the method should override an inherited method. • The compiler generates an error if no matching method exists in the parent class or interface. • It improves code readability and makes the developer's intention clear. • It helps detect spelling mistakes and incorrect method signatures. • Using @Override is considered a best practice in Java development.
Example: Suppose a child class wants to override a method from its parent class. The @Override annotation ensures that the method signature matches the parent method exactly.
Code Example:
class Animal {
void makeSound() {
System.out.println("Animal Sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Dog Barks");
}
}
public class Demo {
public static void main(String[] args) {
Animal animal = new Dog();
animal.makeSound();
}
}Output:
Dog Barks
How @Override Helps:
Correct Override:
class Parent {
void display() {
}
}
class Child extends Parent {
@Override
void display() {
}
}The compiler confirms that display() correctly overrides the parent method.
Incorrect Override:
class Parent {
void display() {
}
}
class Child extends Parent {
@Override
void disply() {
}
}Compilation Error:
method does not override or implement a method from a supertype
The annotation immediately catches the spelling mistake.
Benefits of Using @Override:
• Prevents accidental method signature mismatches • Improves code maintainability • Makes inheritance relationships clear • Helps detect errors at compile time • Encourages cleaner and safer code
Interview Tip: A concise interview answer is:
"@Override is an annotation that tells the compiler a method is intended to override a superclass method or implement an interface method. It helps detect errors such as incorrect method names or parameter lists and improves code readability and reliability."