thumbnail

Method Overriding In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Method overriding is a mechanism by which a subclass can override instance methods, getters, setters by using method overriding.

By using method overriding, individual subclass can specify what behaviour they want to achieve with the overridden method.

The @override annotation

The @override annotation is used for indicating that a method is intentionally overridden.

Refer to program given below to understand where to put this annotation.

Rules for overriding a method

  • Return type of the method that is being overridden must be same is the return type specified in the superclass.
  • Number of arguments should be same as overridden method.
  • The data type and the order in which arguments are written for method in superclass and subclass must be same.
  • Method that is being overridden must be defined in the subclass and not the superclass.

Methods that can’t be overridden

Following types of methods can not be overridden in Dart:

  • Static methods of the superclass can not be overridden by the subclass.
  • Final methods of superclass can not be overridden by the subclass.
  • Methods that are not inherited can not be overridden.

Program to demonstrate use of Method Overriding

Program given below demonstrates a simple method that is being overridden by using method overriding:

class Person {
  void sayHello() {
    print('hello from Person!');
  }
}

class Tony extends Person {
  @override
  void sayHello() {
    super.sayHello();
    print('hello fram Tony!');
  }
}

void main() {
  var t = new Tony();
  t.sayHello();
}

Above program produces following output:

hello from Person!
hello fram Tony!