When developing APIs which are publicly used by others, sometimes we have to replace the old APIs with newer, better and more efficient ones. A typical example is changing a method name to a new one which is more accurate or reflects more appropriate programming practices. In such case, we should keep the old method for backward compatibility with the existing users, whilst encourage them to use the alternate version in the Javadoc. This is referred as API deprecation.
Since Java 1.5, programmers can use the @Deprecated annotation type to mark a program’s element (class, method, field and constructor) deprecated. The following are some examples.
Deprecated interface:
@Deprecated interface Kool { // interface methods }
Deprecated class:
@Deprecated class Foo { // class implementation }
class Bar { @Deprecated public void doSomethingWeird() { // old method } public void doSomethingCool() { // new, alternate method } }
class Constant { @Deprecated public static final int MAX_SIZE = 1024; // new, alternate field public static final int MAX_UPLOAD_SIZE = 1024; }
class Car { @Deprecated Car(String color, int length, int width) { } // new, alternate constructor Car(Style style) { } }
Bar b = new Bar(); b.doSomethingWeird();
Note: Path\to\java\file.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details.
class MyCollection { @Deprecated public static final int DEFAULT_CAPACITY = 10; private int initialCapacity = DEFAULT_CAPACITY; }
When using deprecation, it’s a good practice to provide reason for the deprecation and/or recommend alternative solution in the Javadoc of the deprecated element. For example, the following is Javadoc of a deprecated method of String class:
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)
Deprecated.
This method does not properly convert characters into bytes. As of JDK 1.1, the preferred way to do this is via the getBytes() method, which uses the platform's default charset.
Reference: How and When To Deprecate APIs