Skip to main content
The @Override annotation is a built-in Java marker annotation applied to a method declaration to indicate that the method is intended to override or implement a method declared in a superclass or interface. It functions as a strict compiler directive, triggering compile-time signature verification against the parent type hierarchy.

Technical Specifications

  • Package: java.lang.Override
  • Target: @Target(ElementType.METHOD) – It can only be applied to methods. Applying it to classes, fields, or variables results in a compilation error.
  • Retention: @Retention(RetentionPolicy.SOURCE) – It is retained only in the source code and is discarded by the compiler. It is not written to the .class file and is unavailable at runtime via reflection.

Syntax

Compiler Mechanics and Verification Rules

When the Java compiler encounters the @Override annotation, it performs a strict lookup within the type hierarchy. The compilation succeeds only if all the following conditions are met:
  1. Signature Matching: The compiler searches the direct superclass and all implemented interfaces for a method with an identical name and matching parameter types. The parameter types must match exactly after type erasure.
  2. Return Type Compatibility: The return type of the annotated method must be identical to, or a subtype of (covariant return type), the return type declared in the overridden method.
  3. Access Modifiers: The annotated method cannot assign a more restrictive access modifier than the method it overrides (e.g., a protected method in the superclass cannot be overridden as private).
  4. Exception Handling: The annotated method cannot declare any new or broader checked exceptions that are not declared by the overridden method.
If the compiler fails to find a matching method in the supertype hierarchy, or if any of the overriding rules are violated, it throws a fatal compile-time error: method does not override or implement a method from a supertype.

Interface Implementation

Prior to Java 1.6, the @Override annotation was restricted exclusively to overriding methods from a superclass. As of Java 1.6 and later, the compiler specification was updated to allow and verify the @Override annotation on methods that implement a declared method from an interface.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More