25.5 Selected Standard Annotations

The Java SE Platform API provides several predefined annotation types in the java.lang package that can readily be used in the source code. Selected predefined annotations are discussed in this section, but they should already be familiar as they have been previously used in this book. The reader is encouraged to consult the Java SE Platform API documentation for further details.

It is important to note that the standard annotations presented here are all optional, but programmers are encouraged to use them as they improve the quality of the code. If used, the compiler can aid in verifying certain aspects of the code at compile time.

The @Override Annotation

The marker annotation @Override can be used to indicate that the annotated method in a subtype must override an inherited method from a supertype. If that is not the case, the compiler issues an error.

Click here to view code image

public class A {
  public void doThings() {}
}
public class B extends A {
  @Override
  public void dothings() {}         // Wrong method name.
}

Without the @Override annotation, the class B above will compile successfully even though the method dothings() does not really override the method doThings() in the superclass A. With the @Override annotation, the compiler will flag an error that the method does not fulfill the criteria for overriding methods—in this case, the method names do not match.

Basically, the @Override annotation when applied to a method helps to catch any errors in an attempt to override some method in its supertype at compile time, ensuring that the overriding method satisfies the criteria for method overriding (§5.1, p. 196).

A common mistake is to inadvertently overload a method from the supertype when the intention is to override it. A classic example is the equals() method from the Object class that has the header:

Click here to view code image

public boolean equals(Object obj)

Instead, the method declaration at (1) is declared in the Gizmo class below, leading to subtle bugs in the code:

Click here to view code image

class Gizmo {
  public boolean equals(Gizmo obj) { // (1) Overloaded, as parameter doesn’t match.
    // …
  }
}

Best practices advocate that the @Override annotation is always used when overriding a method.

The API of the Override annotation type from the java.lang package is shown below:

Click here to view code image

@Target(ElementType=METHOD)
@Retention(RetentionPolicy=SOURCE)
public @interface Override

Note that the Override annotation type can only be applied to a method. Its retention policy is SOURCE, meaning it is discarded by the compiler once the code is validated—in other words, it is not recorded in the class file and therefore not available at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *