Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

@Override

Marks a method that overrides a method of a parent class or interface. The compiler checks that it really does.

Available since: Java 5

Syntax

@Target(METHOD) @Retention(SOURCE) public @interface Override

Examples

Overriding a parent's method:

class Animal {
    String sound() {
        return "...";
    }
}
 
class Cat extends Animal {
    @Override
    String sound() {
        return "Meow";
    }
}
 
void main() {
    Animal pet = new Cat();
    IO.println(pet.sound());
}

Output:

Meow

A typo in the name: without the annotation you would get a new method, with it a compile error:

class Animal {
    String sound() {
        return "...";
    }
}
 
class Cat extends Animal {
    @Override
    String sond() {
        return "Meow";
    }
}
 
void main() {
    IO.println(new Cat().sound());
}

Output:

Main.java:8: error: method does not override or implement a method from a supertype

Notes

The annotation is optional, but it is always used: it protects against typos and wrong signatures. A classic mistake is equals(Cat other) instead of equals(Object other): that is an overload, not an override, and @Override catches it at once. It works for interface methods too, and for toString() and hashCode() from Object. It does not end up in the compiled class.

See also

  • extends — Declares inheritance: the class gets the parent's fields and methods.
  • implements — Lists the interfaces that a class implements.
  • Object.toString() — Returns a text form of the object; called when printing and when concatenating with a string.
  • Object.equals() — Compares objects by meaning. By default it works like ==, so classes override it.

In the tutorial

  • Annotations — Annotations in Java — @Override, @Deprecated, @FunctionalInterface, @SuppressWarnings, declaring your own annotation, @Retention, @Target and reading annotations at run time.

Thanks for reading!

Donate to the site — we work hard for you.