The @Override Annotation in Java
Last Updated :
10 Jan, 2023
The @Override annotation is a standard Java annotation that was first introduced in Java 1.5. The @Override annotation denotes that the child class method overrides the base class method.
For two reasons, the @Override annotation is useful.
- If the annotated method does not actually override anything, the compiler issues a warning.
- It can help to make the source code more readable.
Why we use @Override annotation:
Because of the following two advantages, using the @Override annotation when overriding a method is considered a best practice for coding in Java:
1) You’ll get a compile-time error if the programmer makes a mistake while overriding, such as using the wrong method name or parameter types. Because you are informing the compiler that you are overriding this method by using this annotation. If you don’t use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method).
2) It improves the code’s readability. If you change the signature of an overridden method, all sub-classes that override it will throw a compilation error, which will eventually lead to you changing the signature in the subclasses. If you have a large number of classes in your application, this annotation will greatly assist you in identifying the classes that need to be changed when a method’s signature is changed.
Syntax:
public @interface Override
Example 1: Without usage of abstract class
Java
import java.io.*;
class ParentClass {
public void display()
{
System.out.println( "We are in base class method" );
}
}
class ChildClass extends ParentClass {
public void display()
{
System.out.println( "We are in child class method" );
}
}
public class GFG {
public static void main(String args[])
{
System.out.println(
"Example of @Override annotation" );
ParentClass obj = new ChildClass();
obj.display();
}
}
|
Output:
Example 2: Using the abstract class
Java
import java.io.*;
abstract class Vehicle {
public abstract void method();
}
class Car extends Vehicle {
public void method()
{
System.out.println( "This is Car" );
}
}
class Bike extends Vehicle {
public void method()
{
System.out.println( "This is Bike" );
}
}
public class GFG {
public static void main(String[] args)
{
Car Carobj = new Car();
Carobj.method();
Bike Bikeobj = new Bike();
Bikeobj.method();
}
}
|
Output
This is Car
This is Bike
Share your thoughts in the comments
Please Login to comment...