Importance of @Override annotation in Java?

JavaObject Oriented ProgrammingProgramming

The @Override annotation is one of a default Java annotation and it can be introduced in Java 1.5 Version. The @Override annotation indicates that the child class method is over-writing its base class method.

The @Override annotation can be useful for two reasons

  • It extracts a warning from the compiler if the annotated method doesn't actually override anything.
  • It can improve the readability of the source code.

Syntax

public @interface Override

Example

class BaseClass {
   public void display() {
      System.out.println("In the base class,test() method");
   }
}
class ChildClass extends BaseClass {
   @Override 
   public void display() {
      System.out.println("In the child class, test() method");
   }
}
// main class
public class OverrideAnnotationTest {
   public static void main(String args[]) {
      System.out.println("@Override Example");
      BaseClass test = new ChildClass();
      test.display();
   }
}

Output

@Override Example
In the child class, test() method
raja
Published on 27-Aug-2019 13:13:45
Advertisements