- @Override annotation in Java
- Example
- Why we use @Override annotation
- Top Related Articles:
- About the Author
- Comments
- Predefined Annotation Types
- Annotation Types Used by the Java Language
- Annotations That Apply to Other Annotations
- Java @Override Annotation
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- 2. @Override Annotation
- 3. Conclusion
@Override annotation in Java
@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.
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Comments
Hi Chaitanya, I would require a clarification from you with respect to the override annotation. You have above quoted as “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”. Because the subclass is already extending the parent class, ideally (without providing annotation) the method however will get overriden as per my understanding when it has implementation. Based on this, Can you please explain me the point sub-class method behaving as new method.
Hi Datt, I guess Chaitanya meant : “When a programmer makes any mistake such as wrong method name, wrong parameter types while overriding and if annotation is not used, programmer won’t know as the compile time error won’t be thrown. And the sub class method would behave as a new method (not the overriding method) in sub class”
If you change displayMethod(String msg) to displayMethod(String msg, String msg2), program gives error of you have @override. If you comment @override program doesn’t give any error and prints as per displayMethod of SubClass.
This is because when you change the signature to displayMethod(String msg, String msg2), you are not overriding the parent class method. @override annotation is used when you are overriding the method in the child class, this is why you get the error. When you remove the annotation, the displayMethod(String msg, String msg2) method is treated as a normal (not overriden) method of child class and you don’t get error. In short “If you use @override annotation on a method that you are not overriding, you will get an error”. For more information, refer this guide: Overriding in Java.
Predefined Annotation Types
A set of annotation types are predefined in the Java SE API. Some annotation types are used by the Java compiler, and some apply to other annotations.
Annotation Types Used by the Java Language
The predefined annotation types defined in java.lang are @Deprecated , @Override , and @SuppressWarnings .
@Deprecated @Deprecated annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation. When an element is deprecated, it should also be documented using the Javadoc @deprecated tag, as shown in the following example. The use of the at sign ( @ ) in both Javadoc comments and in annotations is not coincidental: they are related conceptually. Also, note that the Javadoc tag starts with a lowercase d and the annotation starts with an uppercase D.
// Javadoc comment follows /** * @deprecated * explanation of why it was deprecated */ @Deprecated static void deprecatedMethod() < >>
@Override @Override annotation informs the compiler that the element is meant to override an element declared in a superclass. Overriding methods will be discussed in Interfaces and Inheritance.
// mark method as a superclass method // that has been overridden @Override int overriddenMethod()
While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.
@SuppressWarnings @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would otherwise generate. In the following example, a deprecated method is used, and the compiler usually generates a warning. In this case, however, the annotation causes the warning to be suppressed.
// use a deprecated method and tell // compiler not to generate a warning @SuppressWarnings("deprecation") void useDeprecatedMethod() < // deprecation warning // - suppressed objectOne.deprecatedMethod(); >
Every compiler warning belongs to a category. The Java Language Specification lists two categories: deprecation and unchecked . The unchecked warning can occur when interfacing with legacy code written before the advent of generics. To suppress multiple categories of warnings, use the following syntax:
@SafeVarargs @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not perform potentially unsafe operations on its varargs parameter. When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
@FunctionalInterface @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is intended to be a functional interface, as defined by the Java Language Specification.
Annotations That Apply to Other Annotations
Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined in java.lang.annotation .
@Retention @Retention annotation specifies how the marked annotation is stored:
- RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
- RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
- RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.
@Documented @Documented annotation indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool. (By default, annotations are not included in Javadoc.) For more information, see the Javadoc tools page.
@Target @Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:
- ElementType.ANNOTATION_TYPE can be applied to an annotation type.
- ElementType.CONSTRUCTOR can be applied to a constructor.
- ElementType.FIELD can be applied to a field or property.
- ElementType.LOCAL_VARIABLE can be applied to a local variable.
- ElementType.METHOD can be applied to a method-level annotation.
- ElementType.PACKAGE can be applied to a package declaration.
- ElementType.PARAMETER can be applied to the parameters of a method.
- ElementType.TYPE can be applied to any element of a class.
@Inherited @Inherited annotation indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type. This annotation applies only to class declarations.
@Repeatable @Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use. For more information, see Repeating Annotations.
Java @Override Annotation
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this quick tutorial, we’ll have a look at how to use the @Override annotation.
2. @Override Annotation
In a subclass, we can override or overload instance methods. Overriding indicates that the subclass is replacing inherited behavior. Overloading is when a subclass is adding new behavior.
Sometimes, we’ll overload by accident when we actually intended to override. It’s easy to make this mistake in Java:
public class Machine < public boolean equals(Machine obj) < return true; >@Test public void whenTwoDifferentMachines_thenReturnTrue() < Object first = new Machine(); Object second = new Machine(); assertTrue(first.equals(second)); >>
Surprisingly, the test above fails. This is because this equals method is overloading Object#equals, not overriding it.
We can use the @Override annotation on inherited methods to protect us from this mistake.
In this example, we can add the @Override annotation above the equals method:
@Override public boolean equals(Machine obj)
At this point, the compiler will raise an error, informing us that we aren’t overriding equals like we think.
Then, we can correct our mistake:
@Override public boolean equals(Object obj)
Because of how easy it’s to accidentally overload, it’s a common recommendation to use the @Override annotation on all inherited methods.
3. Conclusion
In this guide, we saw how the @Override annotation works in Java.
The full source code for the examples can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes: