Skip to main content
The @override annotation is a metadata marker used to explicitly indicate that an instance member (method, getter, setter, or variable) in a subclass is intended to replace a member with the identical name in its superclass or implemented interface. When the Dart analyzer encounters the @override annotation, it performs a strict compile-time check against the class hierarchy. If the annotated member does not exist in any direct or indirect supertype, the compiler throws an error. This enforces contract adherence and prevents silent failures caused by typographical errors in method names or upstream changes to superclass signatures.

Syntax and Application

The annotation is placed immediately preceding the member declaration.
class BaseClass {
  String get identifier => 'Base';
  
  void execute(int code) {
    // Implementation
  }
}

class DerivedClass extends BaseClass {
  @override
  String get identifier => 'Derived';

  @override
  void execute(int code) {
    // Overridden implementation
  }
}

Technical Constraints and Rules

  • Target Validity: @override can only be applied to instance methods, instance variables, getters, and setters.
  • Static Members: It cannot be applied to static members, as static members belong to the class itself and do not participate in inheritance or dynamic dispatch.
  • Constructors: It cannot be applied to constructors, including factory constructors.
  • Signature Compatibility: The overriding member must adhere to Dart’s sound typing rules regarding variance:
    • Return Types (Covariance): The return type of the overriding member must be the same as, or a subtype of, the overridden member’s return type.
    • Parameters (Contravariance): The parameter types of the overriding method must be the same as, or a supertype of, the overridden method’s parameters (unless explicitly marked with the covariant keyword).
    • Optional Parameters: The overriding method must accept at least the same optional parameters as the overridden method.

Uniform Access Principle

Because Dart implements the Uniform Access Principle, the @override annotation is valid when crossing member types between fields and accessors. A subclass can override a superclass instance variable with a getter/setter pair, or override a superclass getter with a final instance variable.
class SuperType {
  int value = 0;
}

class SubType extends SuperType {
  @override
  int get value => 42;

  @override
  set value(int v) {
    // Custom setter logic
  }
}
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More