Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 61 ยท Classes and Object-Oriented Dart

Inheritance and Polymorphism

Learn Dart inheritance and polymorphism: extends, super, @override, abstract members, calling parent constructors, covariant parameters and dynamic dispatch.

Inheritance lets one class build on another. A Dog is an Animal, so it can reuse what animals already do and add or change what is specific to dogs. Polymorphism is the payoff: code written against Animal works with every subclass, and each object answers in its own way.

Dart has single inheritance: a class extends exactly one superclass. Other forms of reuse, interfaces and mixins, have their own lessons. Here you will learn extends, super, @override, abstract members and the rules for constructors and parameter types. Dart code is read-only; the stand-ins are TypeScript classes that behave the same way.

extends and override

Use extends to create a subclass. The subclass inherits all non-private members of the parent, and it may replace methods with @override.

DART
class Animal {
  final String name;
  Animal(this.name);

  String speak() => '$name makes a sound';
  String describe() => 'I am $name';
}

class Dog extends Animal {
  Dog(super.name);

  @override
  String speak() => '$name barks';
}

void main() {
  var pet = Dog('Rex');
  print(pet.speak());      // Rex barks
  print(pet.describe());   // I am Rex   (inherited)
}

The @override annotation is not required by the compiler, but the analyzer uses it to catch mistakes: if you misspell speek() it tells you there is nothing to override. Always write it.

Notice Dog(super.name). This is a super parameter: it forwards the argument to the superclass constructor, just like this.name stores into a field. It saves you from writing Dog(String name) : super(name);, which is the older but still valid form.

classDiagram
    class Animal {
        +String name
        +speak() String
        +describe() String
    }
    class Dog {
        +speak() String
    }
    class Cat {
        +speak() String
    }
    Animal <|-- Dog
    Animal <|-- Cat

Dog and Cat inherit from Animal and each override speak().

Constructors and super

Constructors are not inherited. A subclass constructor must call a constructor of the superclass, and if you do not, Dart calls the unnamed, no-argument one, which fails to compile when the parent does not have one.

DART
class Vehicle {
  final int wheels;
  Vehicle(this.wheels);
  Vehicle.bicycle() : wheels = 2;
}

class Car extends Vehicle {
  final String brand;

  Car(this.brand) : super(4);                       // explicit call
}

class Bike extends Vehicle {
  Bike() : super.bicycle();                         // named parent constructor
}

The order is fixed: the subclass's initializer list runs first, then the superclass constructor, then the subclass constructor body. In the initializer list, super(...) must come last. Because of this order, you cannot read this inside the initializer list.

Calling the parent with super

Inside an overriding method, super.method() calls the parent's version. It is the way to extend behavior instead of replacing it.

DART
class Employee {
  final String name;
  final double salary;
  Employee(this.name, this.salary);

  String summary() => '$name earns $salary';
}

class Manager extends Employee {
  final int reports;
  Manager(super.name, super.salary, this.reports);

  @override
  String summary() => '${super.summary()} and manages $reports people';
}

Overriding rules are straightforward. The return type of the override must be the same as, or a subtype of, the parent's return type. Parameter types must be the same or a supertype, so the override accepts at least what the original accepted. Dart also lets you override getters, setters and operators.

TypeScript extends, super and polymorphism (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Kinds of inheritance

A class can extend exactly one superclass in Dart (single inheritance), but the chain can be as deep as you like and many classes can share a parent:

  • Single: Dog extends Animal.
  • Multilevel: Puppy extends Dog, Dog extends Animal. A Puppy is a Dog and an Animal, and it inherits members from both levels.
  • Hierarchical: several children share one parent, such as Dog extends Animal and Cat extends Animal.
  • Multiple inheritance (one class with two parents) is not allowed. To share behaviour from several sources, use mixins and implements (abstract classes and interfaces).
DART
class Animal {
  void breathe() => print('breathing');
}

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

class Puppy extends Dog {
  void play() => print('playing');
}

class Cat extends Animal {}

void main() {
  var p = Puppy();
  p.breathe();        // from Animal, two levels up
  p.bark();           // from Dog
  p.play();
  print(p is Animal); // true
  Cat().breathe();    // hierarchical: Cat shares Animal with Dog
}

Why use super and this

super reaches the parent's version of a member, so a subclass can extend behaviour instead of replacing it, and can pass constructor arguments upward without duplicating the parent's setup. this refers to the current object, which resolves a clash between a parameter and a field and lets an object hand itself to another function or return itself for chaining. Neither is needed when names do not clash.

Polymorphism and dynamic dispatch

A variable of type Animal may hold a Dog, a Cat, or any other subclass. When you call speak() on it, Dart picks the implementation at runtime from the actual object, not from the declared type. This is called dynamic dispatch.

DART
void main() {
  List<Animal> pets = [Dog('Rex'), Cat('Tom'), Animal('Generic')];
  for (var pet in pets) {
    print(pet.speak());       // each object answers with its own version
  }
}

The reverse is not free: you can only call members declared on the static type. To use something specific to Dog you need a type test, which also promotes the variable:

DART
if (pet is Dog) {
  pet.fetch();                // pet is a Dog in this branch
}

Prefer designing the base class so the shared interface is enough. If you find yourself testing is all the time, consider putting the behavior in the classes or look at sealed classes in Class Modifiers: sealed, final, base.

Abstract members and noSuchMethod

A method without a body is abstract and can only live in an abstract class. Subclasses that are not abstract themselves must implement it.

DART
abstract class Shape {
  double get area;                     // abstract getter
  String describe() => 'area ${area.toStringAsFixed(1)}';
}

class Square extends Shape {
  final double side;
  Square(this.side);

  @override
  double get area => side * side;
}

The details of abstract classes and interfaces fill the next lesson, Abstract Classes and Implicit Interfaces. Every class also inherits from Object, which gives you toString(), ==, hashCode and runtimeType; overriding these is covered in Operator Overloading, ==, hashCode and toString.

The covariant keyword

Parameter types normally can only get wider in an override. Sometimes you want a subclass method to accept a narrower type, which is technically unsafe but practically useful. The covariant keyword lets you opt in:

DART
class Animal {
  void chase(Animal other) {}
}

class Cat extends Animal {
  @override
  void chase(covariant Mouse other) {}      // narrower than Animal: allowed
}
class Mouse extends Animal {}

Calling chase through an Animal variable with the wrong kind of animal throws a type error at runtime, so reserve covariant for cases where your design guarantees the match. Dart's generic types are covariant in the same way: a List<Dog> can be used where a List<Animal> is expected.

Composition versus inheritance

Inheritance models "is a". Do not use it only to reuse code. A Stack is not a List in the sense that callers may insert in the middle; it should have a list. Prefer composition (a field holding another object) for "has a", and use interfaces and mixins when you need to share behavior across unrelated classes.

TypeScript Abstract base and overridden members (TypeScript stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the @override annotation do?

    @override is a safety net. If the name or signature does not match anything in the parent, the analyzer reports an error.
  2. 2. What does Dog(super.name); do?

    A super parameter passes the argument straight to the matching parameter of the parent constructor, replacing : super(name).
  3. 3. In what order does construction run for a subclass?

    Initializer lists run first, then the superclass constructor, and finally the subclass constructor body.
  4. 4. A variable declared as Animal holds a Dog. Which speak() runs?

    Dynamic dispatch chooses the method from the runtime class of the object.
  5. 5. When is the covariant keyword useful?

    covariant allows a subclass override to take a subtype of the original parameter, with a runtime check instead of a compile-time guarantee.

Summary

  • A class extends exactly one superclass with extends; members are inherited, constructors are not.
  • Mark overrides with @override; use super.method() to extend rather than replace behavior.
  • Forward constructor arguments with super parameters (Dog(super.name)) or : super(...).
  • Dynamic dispatch picks the method from the runtime class, which gives you polymorphism.
  • Abstract members have no body and must be implemented by concrete subclasses.
  • covariant narrows an override's parameter type, at the cost of a runtime check; prefer composition when the relationship is not truly "is a".

Next, learn how to describe behavior without sharing code in Abstract Classes and Implicit Interfaces.