How Dart class constructors initialized in subclass/superclass

Introduction :

Dart constructors are called when we create an instance of a class. Each class has one default constructor. It is a no-argument constructor and it is invoked if we don’t call any other constructors while creating an object.

We can create one class extending another class. The new class is called subclass and the old class is called super-class. The subclass doesn’t inherits the constructors from the superclass but by default it calls it. In this post, I will show you how the subclass constructors call superclass constructors and their order of execution.

Default constructors in subclass and superclass :

Constructors in a subclass calls the default constructor in the superclass. For example :

class Vehicle {
  Vehicle() {
    print("Vehicle initialized");
  }
}

class Car extends Vehicle {
  Car() {
    print("Car initialized");
  }
}

class Audi extends Car {
  Audi() {
    print("Audi initialized");
  }
}

main() {
  Audi();
}

It will print the below output :

Vehicle initialized
Car initialized
Audi initialized

Here, Vehicle is the main superclass. Car is subclass of Vehicle and Audi is subclass of Car. In the main() function, we are creating one object of Audi. Look how the constructors are called : Vehicle -> Car -> Audi. That means the superclass unnamed, no-argument constructor is called first.

If an initializer list is also used, it will be called before the execution of superclass.

Manually calling a superclass constructor :

We need to manually call one constructor of the superclass if it doesn’t have any unnamed, no-argument constructor. Superclass constructor call is written after a colon (:), before the child class constructor body. super keyword is used for that. For example :

class Car {
  String carColor;

  Car.customConstructor() {
    print("Car customConstructor called");
  }
}

class Audi extends Car {
  Audi.withColor(String color) : super.customConstructor() {
    print("Setting color...");
    this.carColor = color;
  }
}

main() {
  Audi.withColor("red");
}

It will print :

Car customConstructor called
Setting color...

Dart manually call superclass constructor

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊