Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Dart notes · Topic 11 of 19 · 6 min read

Dart inheritance, interfaces and mixins

Dart inheritance notes with examples: extends and super, overriding, polymorphism, abstract classes, implements, mixins with with, and the is and as operators.

Inheritance with extends

Inheritance lets a new class reuse an existing one. The new class (the subclass) gets all the fields and methods of the old one (the superclass) and can add or change some.

class Person {
  final String name;
  Person(this.name);
  void introduce() => print('I am $name.');
}

class Teacher extends Person {
  final String subject;
  Teacher(super.name, this.subject);
  void teach() => print('$name teaches $subject.');
}

void main() {
  var t = Teacher('Mrs Sinha', 'Maths');
  t.introduce();   // inherited
  t.teach();       // added
}
I am Mrs Sinha.
Mrs Sinha teaches Maths.

super.name passes the parameter on to the superclass constructor (Dart 2.17 and later). The older form is Teacher(String name, this.subject) : super(name);. A Dart class can extend only one class.

Overriding and super

A subclass can override a method to change what it does. @override asks the compiler to check that a method with that name really exists above. super.method() calls the superclass version.

class Account {
  double balance = 1000;
  void withdraw(double amt) {
    balance -= amt;
    print('Withdrew $amt, balance $balance');
  }
}

class SavingsAccount extends Account {
  @override
  void withdraw(double amt) {
    if (balance - amt < 500) {
      print('Minimum balance 500 required');
      return;
    }
    super.withdraw(amt);
  }
}

void main() {
  var s = SavingsAccount();
  s.withdraw(300);
  s.withdraw(400);
}
Withdrew 300.0, balance 700.0
Minimum balance 500 required

Polymorphism

A variable of the superclass type can hold any subclass object. Calling a method runs the version of the actual object. This is polymorphism: one call, many forms.

class Shape {
  double area() => 0;
}

class Circle extends Shape {
  final double r;
  Circle(this.r);
  @override
  double area() => 3.14 * r * r;
}

class Square extends Shape {
  final double side;
  Square(this.side);
  @override
  double area() => side * side;
}

void main() {
  List<Shape> shapes = [Circle(2), Square(3)];
  for (var s in shapes) {
    print('${s.runtimeType}: ${s.area()}');
  }
}
Circle: 12.56
Square: 9.0

Abstract classes

An abstract class cannot be turned into an object. It can declare methods with no body, which every concrete subclass must fill in: a contract.

abstract class Payment {
  double get amount;
  void pay();                // no body: subclasses must write it
  void receipt() => print('Receipt for Rs $amount');
}

class UpiPayment extends Payment {
  @override
  final double amount;
  final String upiId;
  UpiPayment(this.amount, this.upiId);

  @override
  void pay() => print('Paid Rs $amount to $upiId');
}

void main() {
  Payment p = UpiPayment(250, 'shop@upi');
  p.pay();
  p.receipt();
}
Paid Rs 250.0 to shop@upi
Receipt for Rs 250.0

Payment() on its own is an error: *The class 'Payment' is abstract and can't be instantiated.*

Interfaces with implements

In Dart every class is also an interface. implements promises to provide every member of another class, but inherits no code: you write all of it. A class may implement many interfaces.

abstract class Printable {
  void printMe();
}

abstract class Shareable {
  String link();
}

class Invoice implements Printable, Shareable {
  final int no;
  Invoice(this.no);
  @override
  void printMe() => print('Printing invoice $no');
  @override
  String link() => 'https://example.com/invoice/$no';
}

void main() {
  var inv = Invoice(42);
  inv.printMe();
  print(inv.link());
}
Printing invoice 42
https://example.com/invoice/42

Mixins with with

A mixin is a bundle of methods (and fields) that can be added to many unrelated classes. Use mixin to declare it and with to add it. A class can use several mixins.

mixin Swimmer {
  void swim() => print('$runtimeType is swimming');
}

mixin Flyer {
  void fly() => print('$runtimeType is flying');
}

class Animal {}

class Duck extends Animal with Swimmer, Flyer {}

class Fish extends Animal with Swimmer {}

void main() {
  Duck()
    ..swim()
    ..fly();
  Fish().swim();
}
Duck is swimming
Duck is flying
Fish is swimming

.. is the cascade operator: it calls several methods on the same object. mixin Logger on Animal restricts a mixin to subclasses of Animal.

is and as

is checks an object's type (and promotes it inside an if); as casts, and throws if wrong.

class Animal {}

class Dog extends Animal {
  void bark() => print('Woof');
}

void main() {
  Animal a = Dog();
  print(a is Dog);
  print(a is Animal);
  if (a is Dog) a.bark();   // promoted to Dog
  (a as Dog).bark();
}
true
true
Woof
Woof

Choosing between the tools

ToolUse when
extendsa true "is a" relationship; reuse code from one parent
abstract classa shared base that must not be created on its own
implementspromise a set of methods without inheriting code; several allowed
with (mixin)share a capability across unrelated classes

Dart 3 class modifiers (interface class, base class, final class, sealed class) control which of these other libraries may use; sealed is covered in the next topic.

Common mistakes

  • Forgetting to call the superclass constructor when it needs arguments.
  • Missing @override, so a typo creates a new method instead of replacing one.
  • Using implements and expecting the code to be inherited.
  • Trying to extend two classes; use one extends plus mixins or interfaces.
  • Using as without checking; prefer if (x is T).

Key points

  • extends inherits fields and methods from one class; super reaches the parent.
  • @override replaces a method; calls run the version of the real object (polymorphism).
  • Abstract classes define contracts and cannot be instantiated.
  • implements takes on a class's interface with no code; many are allowed.
  • Mixins (mixin + with) add reusable behaviour to many classes.
  • is tests a type; as casts.

Practice questions

1. Write Vehicle with a method wheels() returning 0, and Bike and Car that override it to return 2 and 4.
class Vehicle {
  int wheels() => 0;
}

class Bike extends Vehicle {
  @override
  int wheels() => 2;
}

class Car extends Vehicle {
  @override
  int wheels() => 4;
}

void main() {
  for (Vehicle v in [Bike(), Car()]) {
    print(v.wheels());
  }
}
2. What is the difference between extends and implements?

extends inherits the parent's code and allows only one parent. implements inherits no code: the class must write every member itself, and it may implement many interfaces.

3. Why is Shape() an error when Shape is declared abstract?

Abstract classes cannot be instantiated; you must create an object of a concrete subclass.

4. Write a mixin Greets with a method hello() and use it in a class Robot.
mixin Greets {
  void hello() => print('Hello from $runtimeType');
}

class Robot with Greets {}

void main() {
  Robot().hello();   // Hello from Robot
}
5. What does super.withdraw(amt) do inside an overriding method?

It calls the superclass's version of withdraw, so the subclass can add checks and then reuse the original behaviour.