Java @Override Annotation

Introduction

The @Override annotation in Java indicates that a method is intended to override a method in a superclass. It helps ensure that the method correctly overrides the superclass method.

Table of Contents

  1. What is @Override?
  2. Benefits of Using @Override
  3. How to Use @Override
  4. Examples
  5. Conclusion

1. What is @Override?

@Override is an annotation used to signify that a method is overriding a method in its superclass. It provides compile-time checking to ensure the method signature matches.

2. Benefits of Using @Override

  • Compile-Time Checking: Ensures the method signature matches the overridden method.
  • Readability: Makes the code clearer and easier to understand.
  • Maintenance: Helps prevent errors during code refactoring.

3. How to Use @Override

To use @Override, simply place the annotation above the method that overrides a method from the superclass.

4. Examples

Example 1: Correct Usage of @Override

This example demonstrates using @Override to correctly override a method.

class Animal { void sound() { System.out.println("Animal sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Bark"); } } public class OverrideExample { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); // Output: Bark } } 

Example 2: Compile-Time Error Without @Override

This example shows how @Override can help catch errors during compilation.

class Bird { void fly() { System.out.println("Flying"); } } class Sparrow extends Bird { @Override void flly() { // Typo in method name System.out.println("Sparrow flying"); } } public class OverrideErrorExample { public static void main(String[] args) { Sparrow sparrow = new Sparrow(); sparrow.fly(); // Output: Flying } } 

In this example, a compile-time error will occur because flly() does not override fly() due to the typo.

5. Conclusion

The @Override annotation in Java is a valuable tool for ensuring that methods are correctly overridden. It enhances code readability, maintainability, and helps catch errors during compilation, making it an essential practice in Java development.

Leave a Comment

Scroll to Top