CodeBlanks Logo Icon CodeBlanks

Built-in annotations

Learn built-in annotations @Override and @Deprecated.

Built-in annotations

The Java compiler predefines several annotations (markers). They do not change behavior but give the compiler hints and catch mistakes early.

Three core built-ins: @Override checks that a method overrides a superclass method; @Deprecated marks an element that should no longer be used; @SuppressWarnings silences selected warnings. Each starts with @ and is placed just above the modifier.

Silencing warnings with @SuppressWarnings

@SuppressWarnings turns off specific warning kinds. Common values: "unchecked" for raw types, "deprecation" for old API use, "unused" for unused variables.

Example: @SuppressWarnings("unchecked") above a method hides unchecked warnings in that method. It is good practice to suppress at the narrowest scope; apply it to a single method rather than the whole class.

Practice Write toString with @Override

Define a Product class with a name field and a constructor. Mark the toString method with @Override and return "Product: " + name. In main, create a product and print it with System.out.println.

Starter code

Main.java
// Define the Product class
// Override the toString method
// Print to the screen in main

Sample solution

Main.java
public class Product {
    private String name;
    public Product(String name) { this.name = name; }
    @Override
    public String toString() { return "Product: " + name; }
    public static void main(String[] args) {
        System.out.println(new Product("pen"));
    }
}

Expected output

Product: pen

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which annotation makes the compiler check that a method overrides a superclass method?

  • @SuppressWarnings
  • @Deprecated
  • @Override Correct answer
  • @FunctionalInterface

Explanation: @Override tells the compiler to compare the signature with the superclass.

2 Form the @Override marker

Question
public class Animal {
    @____
    public String toString() { return "Animal"; }
}
Answer
public class Animal {
    @Override
    public String toString() { return "Animal"; }
}

Explanation: The @Override marker shows toString is overridden.

3 Match the built-in annotations

Term Meaning
@Override Override check
@Deprecated Deprecated marker
@SuppressWarnings Warning suppression
@FunctionalInterface Single abstract method

All lessons in Advanced