Last Updated:

Overriding methods in Java. Using @Override annotation

Java Annotations were introduced in Java version 1.5 and at the moment the annotation is one of the built-in Java annotations. When we apply this annotation to a method, it tells the compiler that we are trying to override the superclass method.@Override 

Let's see a simple example of overriding a method in Java.

Now let's create a subclass and override the class method.doSomething(String str)MainClass

Note that in the example above, the annotation is commented out.@Override

Now let's create a test class to test the override in the work.

The result of the program:

Here, the mc object is of type , but at run time it is a class object , so when we call the method , Java looks for an implementation in and displays it.MainClassChildClassdoSomething(String str)ChildClass

Now let's change the class method as shown below:doSomething(String str)MainClass

In this case, the compiler will not generate any warnings or errors. The result of this programme will be:

This is because the MainClass method is no longer overridden by the class and therefore the implementation of the .doSomething(Object str)ChildClassMainClass

If you uncomment the annotation in , you will receive the following compilation error message:@OverrideChildClass

The doSomething(String) method of the ChildClass must override or implement the superclass method

It is better to solve such problems at compile time, rather than while the program is running. Therefore, always use an annotation when you try to override a superclass method.@Override