Java Built-in Annotations: @Override, @Deprecated and More
Java built-in annotations are the annotation types that ship with the JDK in the java.lang and java.lang.annotation packages. Some of them talk to the compiler, such as @Override and @SuppressWarnings. Others, called meta-annotations, describe how other annotations behave, such as @Retention and @Target.
Java Annotations explained what annotations are and how retention works. This lesson walks through every built-in annotation you will meet in everyday Java code, with the exact compiler messages each one produces.
Overview of Java Built-in Annotations
| Annotation | Package | Applies to | Purpose |
|---|---|---|---|
@Override | java.lang | Methods | Compile error if the method does not override anything |
@Deprecated | java.lang | Almost any declaration | Marks an API as outdated; callers get warnings |
@SuppressWarnings | java.lang | Classes, methods, fields, variables, parameters | Hides specific compiler warnings |
@SafeVarargs | java.lang | Static, final or private methods and constructors | Promises a generic varargs method is safe |
@FunctionalInterface | java.lang | Interfaces | Compile error if the interface is not functional |
@Retention | java.lang.annotation | Annotation types | How long an annotation is kept |
@Target | java.lang.annotation | Annotation types | Where an annotation may be placed |
@Documented | java.lang.annotation | Annotation types | Show the annotation in Javadoc |
@Inherited | java.lang.annotation | Annotation types | Subclasses inherit a class-level annotation |
@Repeatable | java.lang.annotation | Annotation types | Allow the same annotation more than once |
Note: Annotations in
java.langneed no import. The meta-annotations live injava.lang.annotationand must be imported.
@Override: Catch Overriding Mistakes
@Override tells the compiler that a method is meant to override a method from a superclass or implement one from an interface. If it does neither, compilation fails.
public class Typo {
static class Animal {
String sound() { return "..."; }
}
static class Cat extends Animal {
@Override
String sounds() { // typo: "sounds" instead of "sound"
return "Meow";
}
}
}
Typo.java:7: error: method does not override or implement a method from a supertype
@Override
^
1 error
How it works:
- Without the annotation,
sounds()would compile as a new method, and everyCatwould still say"...". @OverridehasSOURCEretention. It is checked by the compiler and then removed, so it costs nothing at runtime.- Use it on every overriding method, including
toString(),equals()and interface methods.
@Deprecated: Mark Outdated APIs
@Deprecated marks a class, method, field or other declaration that should no longer be used. Since Java 9 it has two elements.
| Element | Type | Default | Meaning |
|---|---|---|---|
since | String | "" | The version in which it was deprecated |
forRemoval | boolean | false | true means it will be deleted in a future version |
public class PaymentService {
public String payWithUpi(double amount) {
return "UPI payment of Rs. " + amount;
}
@Deprecated(since = "3.0")
public String payWithCheque(double amount) {
return "Cheque payment of Rs. " + amount;
}
@Deprecated(since = "2.4", forRemoval = true)
public String payWithDemandDraft(double amount) {
return "DD payment of Rs. " + amount;
}
}
A caller that uses all three methods:
public class Shop {
public static void main(String[] args) {
PaymentService payments = new PaymentService();
System.out.println(payments.payWithUpi(499.0));
System.out.println(payments.payWithCheque(1200.0));
System.out.println(payments.payWithDemandDraft(5000.0));
}
}
Compile with plain javac Shop.java:
Shop.java:6: warning: [removal] payWithDemandDraft(double) in PaymentService has been deprecated and marked for removal
System.out.println(payments.payWithDemandDraft(5000.0));
^
Note: Shop.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warning
Output when run:
UPI payment of Rs. 499.0
Cheque payment of Rs. 1200.0
DD payment of Rs. 5000.0
How it works:
forRemoval = trueproduces a full[removal]warning on every compile, because the code will break once the method is deleted.- Ordinary deprecation produces only a short note. Add
-Xlint:deprecationto see each[deprecation]warning with its line number. - Deprecated code still runs normally. The annotation warns; it never blocks.
Note: Always tell users what to use instead. The Javadoc tag
@deprecated(lowercase, in a comment) is where you write "Use payWithUpi(double) instead". Use both together: the annotation for tools, the tag for people.
@SuppressWarnings: Hide Specific Compiler Warnings
@SuppressWarnings turns off named compiler warnings for the declaration it is placed on. It is common when working with legacy code that uses raw types. Here is a method compiled with all warnings enabled (-Xlint:all):
import java.util.ArrayList;
import java.util.List;
public class SuppressDemo {
static List<String> loadNames() {
List rawList = new ArrayList(); // raw type, as old code often has
rawList.add("Asha");
rawList.add("Ravi");
return rawList; // unchecked conversion
}
public static void main(String[] args) {
System.out.println(loadNames());
}
}
javac -Xlint:all SuppressDemo.java
SuppressDemo.java:7: warning: [rawtypes] found raw type: List
SuppressDemo.java:7: warning: [rawtypes] found raw type: ArrayList
SuppressDemo.java:8: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
SuppressDemo.java:9: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
SuppressDemo.java:10: warning: [unchecked] unchecked conversion
5 warnings
(Each warning also prints the source line; they are shortened here.) Add the annotation to the method and compile again:
@SuppressWarnings({"rawtypes", "unchecked"})
static List<String> loadNames() {
List rawList = new ArrayList();
rawList.add("Asha");
rawList.add("Ravi");
return rawList;
}
Output of javac -Xlint:all SuppressDemo.java: no warnings. Running the program:
[Asha, Ravi]
Common @SuppressWarnings Names
| Name | Hides warnings about |
|---|---|
"unchecked" | Unchecked casts and conversions with generics |
"rawtypes" | Generic types used without type arguments |
"deprecation" | Use of @Deprecated APIs |
"removal" | Use of APIs deprecated with forRemoval = true |
"unused" | Unused variables or methods (used by IDEs) |
"serial" | Missing serialVersionUID in a Serializable class |
"all" | Everything (supported by IDEs; avoid it) |
How it works:
- The
[rawtypes]and[unchecked]labels in each warning are exactly the names you pass to@SuppressWarnings. - The annotation covers only the declaration it sits on. Put it on the smallest scope possible: a local variable or one method, not the whole class, so new problems elsewhere are still reported.
@SafeVarargs: Generic Varargs Without Warnings
A varargs parameter is really an array. When its type is generic, such as T..., Java cannot create a fully typed array, and the compiler warns about possible heap pollution.
import java.util.ArrayList;
import java.util.List;
public class VarargsDemo {
static <T> List<T> listOf(T... items) {
List<T> result = new ArrayList<>();
for (T item : items) {
result.add(item);
}
return result;
}
public static void main(String[] args) {
List<List<String>> batches = listOf(List.of("A", "B"), List.of("C"));
System.out.println(batches);
}
}
javac -Xlint:unchecked VarargsDemo.java
VarargsDemo.java:6: warning: [unchecked] Possible heap pollution from parameterized vararg type T
static <T> List<T> listOf(T... items) {
^
VarargsDemo.java:15: warning: [unchecked] unchecked generic array creation for varargs parameter of type List<String>[]
List<List<String>> batches = listOf(List.of("A", "B"), List.of("C"));
^
2 warnings
The method only reads from the array, so it is safe. Say so with @SafeVarargs:
@SafeVarargs
static <T> List<T> listOf(T... items) {
List<T> result = new ArrayList<>();
for (T item : items) {
result.add(item);
}
return result;
}
Both warnings disappear, at the declaration and at every call site. Output:
[[A, B], [C]]
@SafeVarargs is allowed only on methods that cannot be overridden, because an overriding method could break the promise:
public class BadSafe {
@SafeVarargs
public <T> void printAll(T... items) {
for (T item : items) System.out.println(item);
}
}
BadSafe.java:3: error: Invalid SafeVarargs annotation. Instance method <T>printAll(T...) is neither final nor private.
How it works:
- Valid places are constructors and
static,finalorprivatemethods. - Use it only when the method never stores anything into the varargs array and never lets the array escape.
List.of(...)andArrays.asList(...)in the JDK are declared this way.
@FunctionalInterface: Guarantee One Abstract Method
A functional interface has exactly one abstract method, which is what makes lambdas possible. @FunctionalInterface asks the compiler to check that rule.
@FunctionalInterface
interface DiscountRule {
double apply(double price);
default DiscountRule then(DiscountRule next) { // default methods are allowed
return price -> next.apply(apply(price));
}
}
public class FiDemo {
public static void main(String[] args) {
DiscountRule festive = price -> price * 0.90;
DiscountRule coupon = price -> price - 100;
System.out.println(festive.then(coupon).apply(2000));
}
}
Output:
1700.0
Add a second abstract method and the annotation reports it:
@FunctionalInterface
interface PriceRule {
double apply(double price);
double reverse(double price); // a second abstract method
}
BadFi.java:1: error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
PriceRule is not a functional interface
multiple non-overriding abstract methods found in interface PriceRule
1 error
How it works:
2000 × 0.90 = 1800, then1800 − 100 = 1700. Thethendefault method chains two rules, and default andstaticmethods do not count against the "one abstract method" rule.- Without the annotation, the interface would still work with lambdas. The annotation protects it from someone accidentally adding a second abstract method later, which would break every lambda that uses it.
- See Java Functional Interfaces for the built-in ones like
FunctionandPredicate.
Meta-Annotations: @Retention, @Target, @Documented
Meta-annotations go on annotation declarations (@interface) to configure them.
| Meta-annotation | Values | Default if omitted |
|---|---|---|
@Retention | RetentionPolicy.SOURCE, CLASS, RUNTIME | CLASS (not visible to reflection) |
@Target | ElementType.TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE, MODULE, RECORD_COMPONENT | Any declaration context |
@Documented | none | Annotation is not listed in Javadoc |
@Target enforces placement at compile time:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@interface Timed { }
@Timed // not allowed: Timed is only for methods
public class TargetErr { }
TargetErr.java:7: error: annotation interface not applicable to this kind of declaration
@Timed // not allowed: Timed is only for methods
^
1 error
How it works:
@Target(ElementType.METHOD)lists the only place@Timedmay appear. Pass several values in braces, for example@Target({ElementType.TYPE, ElementType.METHOD}).@Documentedmakes Javadoc show the annotation on each documented element.@Deprecatedis documented, which is why deprecated methods display it in API docs.- The next lesson, Java Annotation Targets, covers every
ElementTypein detail.
@Inherited: Class Annotations Passed to Subclasses
By default, an annotation on a class is not visible on its subclasses. @Inherited changes that for class-level annotations.
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Audited { }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Cached { }
@Audited
@Cached
class BaseRepository { }
class OrderRepository extends BaseRepository { }
public class MetaDemo {
public static void main(String[] args) {
for (Class<?> type : new Class<?>[] {BaseRepository.class, OrderRepository.class}) {
System.out.printf("%-16s audited=%-5b cached=%b%n", type.getSimpleName(),
type.isAnnotationPresent(Audited.class),
type.isAnnotationPresent(Cached.class));
}
}
}
Output:
BaseRepository audited=true cached=true
OrderRepository audited=true cached=false
How it works:
OrderRepositoryhas no annotations of its own, yet it reportsaudited=truebecause@Auditedis@Inherited.@Cachedis not inherited, so the subclass reportsfalse.@Inheritedworks only for annotations on classes and only throughextends. It has no effect on methods, fields or interfaces.
@Repeatable: Use the Same Annotation Twice
Normally an annotation may appear only once per declaration. @Repeatable (Java 8+) allows repeats. It needs a container annotation whose value() is an array of the repeatable type.
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.Arrays;
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Schedules.class) // the container that holds repeated values
@interface Schedule {
String day();
String time();
}
@Retention(RetentionPolicy.RUNTIME)
@interface Schedules {
Schedule[] value();
}
public class RepeatDemo {
@Schedule(day = "MON", time = "09:00")
@Schedule(day = "THU", time = "18:30")
static void backupDatabase() { }
public static void main(String[] args) throws NoSuchMethodException {
var method = RepeatDemo.class.getDeclaredMethod("backupDatabase");
for (Schedule schedule : method.getAnnotationsByType(Schedule.class)) {
System.out.println("Backup on " + schedule.day() + " at " + schedule.time());
}
System.out.println("getAnnotation(Schedule) = " + method.getAnnotation(Schedule.class));
System.out.println("Stored as: " + Arrays.toString(method.getAnnotations()));
}
}
Output:
Backup on MON at 09:00
Backup on THU at 18:30
getAnnotation(Schedule) = null
Stored as: [@Schedules({@Schedule(day="MON", time="09:00"), @Schedule(day="THU", time="18:30")})]
How it works:
- The compiler silently wraps the two
@Scheduleannotations into one@Schedulescontainer, as the last line shows. - That is why
getAnnotation(Schedule.class)returnsnull. Always read repeatable annotations withgetAnnotationsByType(...), which unwraps the container for you. - The container must have the same or longer retention and a compatible target.
Real-World Example: A Notification Channel Registry
This example uses every built-in annotation from the lesson in one small program. A notification center scans its channels, reads the owning team (inherited), the supported regions (repeatable), and skips channels that are marked for removal.
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
// ---- annotation types built with meta-annotations ----
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface OwnedBy {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(Regions.class)
@interface Region {
String value();
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Regions {
Region[] value();
}
// ---- the channel contract ----
@FunctionalInterface
interface Channel {
String send(String user, String message);
}
@OwnedBy("notifications-team")
abstract class BaseChannel implements Channel {
@Override
public String toString() {
return getClass().getSimpleName();
}
}
@Region("IN")
@Region("AE")
class SmsChannel extends BaseChannel {
@Override
public String send(String user, String message) {
return "SMS to " + user + ": " + message;
}
}
@Region("GLOBAL")
class EmailChannel extends BaseChannel {
@Override
public String send(String user, String message) {
return "Email to " + user + ": " + message;
}
}
@Deprecated(since = "5.0", forRemoval = true)
@Region("IN")
class FaxChannel extends BaseChannel {
@Override
public String send(String user, String message) {
return "Fax to " + user + ": " + message;
}
}
public class NotificationCenter {
@SafeVarargs
static <T> List<T> listOf(T... items) {
List<T> result = new ArrayList<>();
for (T item : items) {
result.add(item);
}
return result;
}
@SuppressWarnings("removal") // we use FaxChannel on purpose, to report it
public static void main(String[] args) {
List<BaseChannel> channels = listOf(new SmsChannel(), new EmailChannel(), new FaxChannel());
for (BaseChannel channel : channels) {
Class<?> type = channel.getClass();
OwnedBy owner = type.getAnnotation(OwnedBy.class); // inherited
List<String> regions = Arrays.stream(type.getAnnotationsByType(Region.class))
.map(Region::value)
.toList();
Deprecated deprecated = type.getAnnotation(Deprecated.class);
System.out.printf("%-13s owner=%s regions=%s%n", channel, owner.value(), regions);
if (deprecated != null && deprecated.forRemoval()) {
System.out.println(" SKIPPED: deprecated since " + deprecated.since() + ", marked for removal");
continue;
}
System.out.println(" " + channel.send("Asha", "Your order ORD-1001 has shipped"));
}
Channel console = (user, message) -> "Console to " + user + ": " + message; // lambda works
System.out.println(console.send("Ravi", "Welcome to GOCOURSE"));
}
}
javac -Xlint:all NotificationCenter.java
java NotificationCenter
Output (the compile step prints no warnings):
SmsChannel owner=notifications-team regions=[IN, AE]
SMS to Asha: Your order ORD-1001 has shipped
EmailChannel owner=notifications-team regions=[GLOBAL]
Email to Asha: Your order ORD-1001 has shipped
FaxChannel owner=notifications-team regions=[IN]
SKIPPED: deprecated since 5.0, marked for removal
Console to Ravi: Welcome to GOCOURSE
How it works:
@OwnedBywith@Inherited. It is written once onBaseChannel, yet every subclass returns it fromgetAnnotation.@Documentedwould also list it in the generated Javadoc.@Regionwith@Repeatable.SmsChanneldeclares two regions.getAnnotationsByTypereturns both, and a stream maps them to[IN, AE].@Deprecated(forRemoval = true). The registry reads it at runtime and skipsFaxChannel, while the compiler would warn anyone who uses it.@SuppressWarnings("removal"). The program creates aFaxChannelon purpose, so the[removal]warning is suppressed onmainonly. Remove the annotation andjavacprintswarning: [removal] FaxChannel in unnamed package has been deprecated and marked for removal.@SafeVarargs.listOfisstaticand only reads its array, so-Xlint:allstays silent.@FunctionalInterfaceand@Override.Channelhas exactly one abstract method, so theconsolelambda compiles, and everysendimplementation is checked by@Override.
In Java Custom Annotations you will design annotation types like @OwnedBy and @Region from scratch, including elements, defaults and runtime processing.