The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Learning the Java Language
Lesson: Classes and Inheritance

Annotations

Introduced in J2SE 5.0, annotations provide a way for programmers to instruct the compiler on how to handle certain situations. For example, an annotation can indicate that a particular method or class should be overridden in a subclass or that certain compiler error messages shouldn't be printed. Defining your own annotation is an advanced technique that won't be described here, but there are three useful annotations built-in to release 5.0 that will be discussed.

Annotations use the form @annotation and can be applied to methods or classes. For example:

@Override class Cat extends Pet {
}
or
@Override void feedTheDog() { }
The following example illustrates all three built-in annotation types, using methods:
import java.util.List;

class Food {}
class Hay extends Food {}
class Animal {
    Food getPreferredFood() {
        return null;
    }
    @Deprecated
    static void deprecatedMethod() {
    }
}
class Horse extends Animal {
    Horse() {
        return;
    }
    @Override //compiler error if getPreferredFood
              //overloaded, not overridden
    //Notice the return type is different
    //(covariant return type).
    Hay getPreferredFood() {
        return new Hay();
    }
    @SuppressWarnings({"deprecation", "unchecked"})
    void useDeprecatedMethod(List raw) {
        //deprecation warning - suppressed
        Animal.deprecateMethod();
        //unchecked warning - suppressed
        raw.add(new Horse());
    }
}

For more information on annotations, see JSR 175: A Metadata Facility for the Java Programming Language (outside of the tutorial). It is strongly recommended that you suppressed warnings only where necessary. For example, using the SuppressWarnings annotation on the entire Horse class is not recommended because genuine errors in the code might be hidden.

For more information on annotations, see the 5.0 Release Notes (outside of the tutorial).

[PENDING: Is there any other place I can send them to for information on annotations?]


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.