Super Constructor

The Derived class can inherit all properties and behavior of the base class expect base class constructor.

The superclass constructor can be invoked in the subclass by using the super() constructor. We can access both non-parameterized and parameterized constructor of the superclass.

  1. Implicit super
  2. When creating a subclass constructor, if you don't explicitly call a superclass constructor with super , then Dart will insert an implicit call to the no-arg "default" superclass constructor:

    Example:

    class Base {

      Base() {

        print("Base Constructor");

      }

    }

     

    class Derived extends Base {

      Derived() {

        print("Derived Constructor");

      }

    }

     

    void main() {

      var object = Derived();

    }



    Base Constructor
    Derived Constructor

  3. Explicit super
  4. If the Base class constructor consists of parameters then we require to call super constructor with args in to invoke Base class constructor in the derived class explicitly.

    Example:

    class Base {

      Base(int x) {

        print("Base Constructor");

        print("I have $x");

      }

    }

     

    class Derived extends Base {

      Derived(aux, aux2) : super(aux) {

        print("Derived Constructor");

        print("I have $aux2");

      }

    }

     

    void main() {

      var object = Derived(48);

    }



    Base Constructor
    I have 4
    Derived Constructor
    I have 8