@Deprecated annotation is used for informing compiler that the particular method, class or field is deprecated and it should generate a warning when someone try to use any of the them.
What is the meaning of “Deprecated”?
A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future.
Java provides a way to express deprecation because, as a class evolves, its API (application programming interface) inevitably changes: methods are renamed for consistency, new and better methods are added, and fields change. But such changes introduce a problem. You need to keep the old API around until developers make the transition to the new one, but you don’t want them to continue programming to the old API, in such case you can deprecate the particular item using built-in annotation. Source.
How to Deprecate?
We deprecate a method, class or field by using @Deprecated annotation and we use @deprecated Javadoc tag in the comment section to inform the developer, the reason of deprecation and what can be used in place of this deprecated method, class or field. Lets take an example:
Example
class DeprecatedDemo { /* @deprecated This field is replaced by * MAX_NUM field */ @Deprecated int num=10; final int MAX_NUM=10; /* @deprecated As of release 1.5, replaced * by myMsg2(String msg, String msg2) */ @Deprecated public void myMsg(){ System.out.println("This method is marked as deprecated"); } public void myMsg2(String msg, String msg2){ System.out.println(msg+msg2); } public static void main(String a[]){ DeprecatedDemo obj = new DeprecatedDemo(); obj.myMsg(); System.out.println(obj.num); } }
Output:
This method is marked as deprecated 10
In the above example we have a deprecated method and a deprecated field. As you can see that we have marked both of them using @Deprecated annotation and in the comment section we have used @deprecated javadoc tag (for documentation purpose) to inform the programmer what to use in place of it.
Note: When you use deprecated types(method, class or field) the compiler would not throw a compilation error it would just show a warning to let you know that this is deprecated and you may have a better alternative of it, which you can find out in the comments section by looking for @deprecated tag.
Reference:
How and When To Deprecate APIs
Leave a Reply