Sitemap

Annotations in Java

2 min readOct 4, 2024

--

Annotations in Java are not something that effects execution of your program, but they are ways to give some messages to compile or run time environment. Annotations are also called as meta data.

There are many annotations in Java, like : @Override, @Deprecated, etc..

Suppose I have a class A and class B (which extends class A), we want to override a method of class A in class B.

//Test.java
class A
{
public void show()
{
System.out.println("In A class");
}
}

class B extends A
{
public void shows()
{
System.out.println("In B class");
}
}

class Test
{
public static void main(String args[])
{
B b = new B();
b.show();
}
}
/*
Output:
In A class
*/

In above we wanted to override show() method in class A but due to typo it didn’t happen and this lead to logical error. In this example it might look simple to solve error (replace shows with show)but in larger projects with larger method’s name, it becomes very difficult to solve such logical error.

So, in order to handle such problems annotations can be used. In context to above example adding annotation @Override, before defining overloaded method will give an compile time error if method below it, is not present in parent class.

Press enter or click to view image in full size

There are many other annotations in Java at different levels like class level, method level, variable level. Like @Deprecated which gives use a message that the class is Deprecated (i.e. class will soon be discontinued or better alternatives are available.)

Get Raj R. Sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

If we use @Deprecated annotation it gives following warning:

Press enter or click to view image in full size

There are many annotations in Java which you can explore:

Press enter or click to view image in full size
Class Level Annotations
Press enter or click to view image in full size
Method level Annotations

Annotations are mainly used in Java frameworks.

This article briefly explains about annotations in Java. There is much more to explore in Java.

Keep Coding…

--

--

Raj R. Sharma
Raj R. Sharma

Written by Raj R. Sharma

Passionate Computer Engineering Student exploring the world of software. LinkedIn: https://www.linkedin.com/in/raj-r-sharma/