@Override
Annotation
- The
@Override
annotation in Java is used to indicate that a method in a subclass is overriding a method from its superclass. - This annotation is not mandatory, but it is highly recommended because it provides compile-time validation.
Why is @Override
Important?
1. Compile-Time Validation:
- Purpose: The
@Override
annotation ensures that the method is correctly overriding a method in the superclass. If there is a mismatch in the method signature (e.g., incorrect parameters or spelling errors), the compiler will throw an error. - Example:
```java
public class Parent {
public void display() {
System.out.println("Display from Parent");
}
}
public class Child extends Parent {
@Override
public void display() {
System.out.println("Display from Child");
}
}
``
Here,
@Overrideensures that the
display()method in
Childcorrectly overrides the method in
Parent`.
2. Error Prevention:
- Purpose: Without
@Override
, you might accidentally introduce new methods instead of overriding existing ones due to method signature mismatches. This can lead to bugs that are difficult to detect. - Example (Without
@Override
):
java
public class Child extends Parent {
// Method misspelled; without @Override, the compiler will not catch it
public void disply() {
System.out.println("Misspelled Method");
}
}
Here, the method disply()
won’t override display()
from Parent
because of the typo. The lack of @Override
will not cause a compile-time error, potentially leading to unexpected behavior.
3. Improves Code Readability:
- Purpose: The
@Override
annotation makes it clear to other developers that a method is meant to override a method from the superclass, improving the code’s readability and maintainability. - Example:
java
@Override
public String toString() {
return "Custom String Representation";
}
When to Use @Override
:
- Use
@Override
when you are overriding a method from a superclass or implementing a method from an interface. It ensures that the method adheres to the correct signature and intent.