Last Updated:

Why use @Override annotation in Java [Core Java]

The @Override annotation was introduced in Java 5. This annotation marks methods that are overridden in heirs.

How to use @Override annotation

 

Consider the standard AutoCloseable interface:

 

 
public interface
void close() throws Exception;
}
As you can see, this interface defines one close method.
Now let's create your own Resource class and specify that it implements the AutoCloseable interface:
public class Resource implements AutoCloseable {
}

Now, in order for the code to compile, we need to define the close method. If you generate a method stub using your IDE, the method will automatically be annotated

@Override:
public class Resource implements AutoCloseable
{
@Override
public void close() throws Exception {
code
}
}

Function 1: Labeling of overridden methods

 

As you can see, the annotation means that the close method has been overridden. This gives an additional hint to the programmer that the method was declared in some ancestor of this class.

Feature 2: Protection against overriding of the wrong method

 

The second, no less important function of annotation @Override is protection against overriding of the wrong method by the programmer's mistake.

In the same Resource class, rename the close() method to close2():

public class Resource implements AutoCloseable {
 
 
@Override
public void close2() throws Exception {
code
}
}

Your IDE will highlight the line with the @Override annotation, signaling to you that the close2() method does not exist in the ancestors of the Resource class. Thus, the compiler warns us about a potential error that could occur due to the fault of the programmer.

Conclusion

The @Override annotation simultaneously denotes overridden (implementable) methods in descendants and prevents potential errors that may have occurred when defining a method with a different signature.