Dart – Override Method

To override method of a supervisor class by subclass, define a method in subclass, where name of the method, parameters in the method, and the return type of the method matches.

Sample

The following is a sample code snippet to override display() method of class A by class B.

class A {
  void display(int x) {
    //code
  }
}

class B extends A {
  void display(int x) {
    //code
  }
}

Examples

In the following example, we take two classes: A and B. B extends A, therefore, B is subclass and A is superclass. Class A contains a method display(). Class B overrides this method by defining a method with the same name, same set of parameters, and the same return type.

main.dart

class A {
  void display(int x) {
    print('Calling method from class A');
  }
}

class B extends A {
  void display(int x) {
    print('Calling method from class B');
  }
}

void main() {
  var b = new B();
  b.display(5);
}

Output

Calling method from class B

Conclusion

In this Dart Tutorial, we learned how to override a method of superclass in subclass, with examples.