thumbnail

Default and Parameterized Constructors In Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Use of Constructor In Dart

A constructor is a special method of a class that is used for initializing the variables of the class. A constructor does not allow specifying custom return type, the return type of the constructor is the class itself.

If no constructor is defined by the programmer then default constructor is the no-argument constructor.

Constructor is called whenever you try to initialize an object.

Default Constructor

// program to demonstrate default constructor

class Square {
  Square();
}

Even if not defined, every dart class has a default constructor as shown in above code.

Parameterized Constructor

A constructor that accepts parameters is called parameterized constructor. Similar to functions, constructors can also accept parameters. Parameterized constructors allows a programmer to initialize un-initialized variables with a custom value.

Given below are some programs that demonstrate use of parameterized constructors in Dart.

Program Using Parameterized Constructor

Program to demonstrate use of Parameterized Constructor in Dart:

// program to demonstrate use of Parameterized constructor in Dart

class Person {
  final String name;

  // Parameterized constructor
  Person(this.name);
}

main(List<String> args) {
  var person = new Person('abc');
  print('person.name is: ${person.name}');
}

Above program produces following output:

person.name is: abc

Program Explanation: As shown in above program, a constructor is defined.

Instance of a class is created using the new keyword:

var person = new Person('abc');

However, this new keyword is optional in new versions of Dart and can be omitted to make instance of above class appear as:

var person = Person('abc');

Constructors Are Not Inherited

When you define a class that extends from another, then parameterized constructor of the parent class is not inherited.

Instead, you are asked to define a new constructor.

// program to demonstrate use of parameterized constructor in Dart

class Person {
  final String name;

  // parameterized constructor
  Person(this.name);
}

class John extends Person {
  John(String name) : super(name);
}

main(List<String> args) {
  var person = new John('john');
  print('person.name is: ${person.name}');
}

Above program produces following output:

person.name is: john

As shown in above program, class John extends from class Person, therefore it is mandatory to define a new parameterized constructor in the extended class John because parameterized constructors are not inherited by child classes.