@Override Annotation in Java: What It Is and How It Works
@Override annotation in Java tells the compiler that a method is meant to replace a method in a parent class. It helps catch mistakes by checking if the method actually overrides a method from a superclass or interface.How It Works
Think of @Override as a label you put on a method to say, "This method is replacing one from the parent class." When you write this annotation, Java checks if the method really exists in the parent class or interface. If it doesn't, the compiler gives an error, helping you avoid mistakes like misspelling the method name or using the wrong parameters.
This is like telling a friend you will take over their job task, and they confirm if you got the right task. If you got it wrong, they immediately tell you so you can fix it before starting.
Example
This example shows a class Dog overriding the sound() method from its parent class Animal. The @Override annotation ensures the method is correctly overriding.
class Animal { void sound() { System.out.println("Animal makes a sound"); } } class Dog extends Animal { @Override void sound() { System.out.println("Dog barks"); } } public class Main { public static void main(String[] args) { Animal myDog = new Dog(); myDog.sound(); } }
When to Use
Use @Override whenever you want to replace a method from a parent class or implement a method from an interface. It helps catch errors early, especially in large projects where many classes inherit from others.
For example, if you are customizing behavior in a subclass or implementing interface methods, adding @Override makes your code safer and easier to understand.
Key Points
- Prevents errors: Compiler checks if the method truly overrides a parent method.
- Improves readability: Shows clearly which methods are overrides.
- Optional but recommended: Code works without it, but it is best practice to use.
- Works with classes and interfaces: Can override superclass or implement interface methods.