Dart – Inheritance

Inheritance is a concept where it is possible to inherit properties and methods of a class by another class. The class that can inherit is called subclass, and the class that lets its properties and methods inherited to another is called superclass.

extends keyword is used to define inheritance to one class from another class.

Syntax

The syntax to inherit from class A by class B using extends keyword is

class A {
  ...
}

class B extends A {
  ...
}
ADVERTISEMENT

Examples

In the following example, we take two classes: A and B. B extends A, therefore, B is sub-class and A is super-class. Class A contains a method add(). Class B contains sub() method. We shall create an object of type B, and access the methods of class A using this object, since B extends/inherits A.

main.dart

class A {
  void add(int x, int y) {
    print(x + y);
  }
}

class B extends A {
  void sub(int x, int y) {
    print(x - y);
  }
}

void main() {
  var b = new B();
  b.add(5, 2);
  b.sub(5, 2);
}

Output

7
3

Conclusion

In this Dart Tutorial, we learned the concept of Inheritance in Dart, and how to inherit from a class, with examples.