@Override annotation in Java
BY CHAITANYA SINGH | FILED UNDER: JAVA TUTORIALS
@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method. Here we will discuss why we should use @Override annotation and why it is considered as a best practice in java coding.
Lets take an example first to understand how it is used then we will discuss it in detail:
Example
class ParentClass { public void displayMethod(String msg){ System.out.println(msg); } } class SubClass extends ParentClass { @Override public void displayMethod(String msg){ System.out.println("Message is: "+ msg); } public static void main(String args[]){ SubClass obj = new SubClass(); obj.displayMethod("Hey!!"); } }
In the above example we are overriding a method displaymethod()
in the child class. Even if we don’t use the @Override annotation, the program would still run fine without any issues, You would be wondering the why do we use this annotation at all. Lets discuss about it:
Why we use @Override annotation
Using @Override annotation while overriding a method is considered as a best practice for coding in java because of the following two advantages:
1) If programmer makes any mistake such as wrong method name, wrong parameter types while overriding, you would get a compile time error. As by using this annotation you instruct compiler that you are overriding this method. If you don’t use the annotation then the sub class method would behave as a new method (not the overriding method) in sub class.
2) It improves the readability of the code. So if you change the signature of overridden method then all the sub classes that overrides the particular method would throw a compilation error, which would eventually help you to change the signature in the sub classes. If you have lots of classes in your application then this annotation would really help you to identify the classes that require changes when you change the signature of a method.
转载自:https://beginnersbook.com/2014/07/override-annotation-in-java/