Skip to content

Override Annotation


layout: default title: @Override


In Java 5, the designers of the language added the @Override annotation.

  • This annotation is placed before, or over, a method.
public class DataAnalyst extends Employee {
  // ...
  @Override
  public String getInfo() {
    return super.getInfo() + " " + securityClearance;
  }
}

@Override tells the compiler to check if the method is actually overriding a superclass's method.

  • If the method is not overriding a parent method (meaning it does not have the same signature), you will see a compiler error.

Practice Exercise

Note that @Override does not make the method an overriding method. It only allows the compiler to ensure that what we expect to be an override really is.

This annotation keeps us from accidentally overloading a method, which could lead to unexpected behavior.

public class Employee extends Person {
  // ...
  public void executeJob(String data) {
    System.out.println("Executing job " + data);
  }
}

public class SoftwareDeveloper extends Employee {
  public String produceSoftware() {
    return "Hello World!";
  }
  // NOT AN OVERRIDE - different signature is an "overload"
  public void executeJob() {
    System.out.println(produceSoftware());
  }
}


Drill

Polymorphism/com.example.polymorphism.drills.employee.DataAnalyst * Add @Override over executeJob(String). * Add @Override over getInfo().

Polymorphism/com.example.polymorphism.drills.employee.DatabaseAdmin * Add @Override over executeJob(String)

Polymorphism/com.example.polymorphism.drills.employee.SoftwareDeveloper * Add @Override over executeJob(String) and getInfo().

Polymorphism/com.example.polymorphism.drills.employee.Employee

  • Add @Override over getInfo().
  • Try to add @Override over executeJob(String).
  • Determine why this does not work.
  • Remove the annotation.

(Solution: Employee3.java, DataAnalyst3.java, DatabaseAdmin3.java, SoftwareDeveloper3.java)


Prev -- Up -- Next