Constructors in Dart Programming

Dart ProgrammingServer Side ProgrammingProgramming

Constructors are methods that are used to initialize an object when it gets created. Constructors are mainly used to set the initial values for instance variables. The name of the constructor is the same as the name of the class.

Constructors are similar to instance methods but they do not have a return type.

All classes in Dart have their own default constructor, if you don't create any constructor for a class, the compiler will implicitly create a default constructor for every class by assigning the default values to the member variables.

We can create a constructor in Dart something like this −

class SomeClass {
   SomeClass(){
      // constructor body
   }
}

There are two important rules that we should keep in mind when creating a constructor in Dart, these are −

  • The name of the constructor should be the same name as the class name.

  • The constructor cannot have an explicit return type.

Types of Constructors

In total there are three types of constructors present in Dart, these mainly are −

  • Default Constructor

  • Parameterized Constructor

  • Named Constructor

Default Constructor

A constructor with no parameter is known as the default constructor. If you don't create a constructor explicitly, the compiler will create one implicitly.

Example

 Live Demo

class Student {
   Student(){
      print("Inside Student Constructor");
   }
}

void main(){
   Student st = new Student();
}

Output

Inside Student Constructor

Parameterized Constructor

We can also have constructors that take parameters, that can later be used to initialize instance variables.

Example

 Live Demo

class Student {
   Student(String name){
      print("Student name : ${name}");
   }
}

void main(){
   Student st = new Student("Tuts!");
}

Output

Student name : Tuts!

Named Constructor

In Dart, named constructors are mainly used to define multiple constructors.

Example

 Live Demo

void main() {

   Student emp1 = new Student();
   Student emp2 = new Student.namedConst('ST001');
}

class Student{
   Student() {
      print("Inside Student Constructor");
   }

   Student.namedConst(String stCode) {
      print(stCode);
   }
}

Output

Inside Student Constructor
ST001
raja
Published on 21-May-2021 12:40:29
Advertisements