×

Dart Construtors

Constructors are the very important concept in any programming language. They are the special functions created in the classes to allocate memory to the objects of that class when created in the program. In object - oriented programming, as soon as we create an object, the compiler automatically invokes the constructor, this constructor is known as the default constructor. All classes have their default constructor which is created by the compiler when class is called, moreover one can also define their own constructor explicitly. In that case, the default constructor will be ignored and the compiler won’t invoke it.

Remember that the constructors have the same name as the class name and don’t have any return type.

Consider the following syntax of creating a constructor :

Syntax :

class_name( < parameters > )

{

   // Body of the constructor

}

In the above syntax, ‘class_name’ refers to the name of the class whose constructor is being created.

‘<parameters>’ refer to the list of arguments that are passed to the constructor. However, it is an optional feature to pass parameters to the constructor. The default constructor has no parameter defined in it.

The body of the constructor refers to the lines of code that defines the functioning of the constructor. The constructor is called when an object is created.

Constructors don’t have any return type and therefore, we did not mention anything related to the return type in the syntax as well.

Program

Consider the following code in Dart that explains the concept of constructors

// Defining the class student

class student

{

  /* defining the constructor of the class student

   * with the same name as of the class, and no r

   * return type */

student( )

{

    /* Everytime the constructor is invoked, this

     * line is printed */

    print( ' Constructor is being invoked ! ' ) ;

  }

   

  // initialzing a string str

  String str = ' NULL ' ;

   

  // Creating Function inside class

  void display(){

    print( " The string is $str " ) ;

  }

}

  void main( )

{

  // Creating an object s1 of the class student

  student s1 = new student( );

   

  /* Accessing the instance variable str using

   * the object and intializing it with some

   * value */

  s1.str = ' This tutorial explains constructor also ! ' ;

   

  /* Accessing the instance function display using

   * the object to display the value of string */

  s1.display( ) ;

}

Output :

Constructor is being invoked !

The string is  This tutorial explains constructor also !

There are three types of constructors in Dart :

  1. Default Constructor
  2. Parametrized Constructor
  3. Named Constructor

Default Constructor :

As mentioned above, every class has a default constructor that does not have any parameter or return type. It is invoked by the compiler automatically even if we do not declare or define it explicitly.

Syntax :

class ClassName { 

   ClassName( )

  // body of the constructor

}

Consider the following code in Dart that explains the concept of default constructor

Example :

/* A program to illustrate the concept of

* default constructor.

* Consider the definition of the class student */

class student

{

  // default constructor of the class

  student( )

{

    print( ' This is the default constructor ' ) ;

  }

}

  void main( )

{

      // declaring an object of the class

  student s1 = new student( ) ;

}

Output :

This is the default constructor

Explanation :

Even though we did not explicitly call any constructor, the compiler invokes it automatically.

Parameterized Constructor :

In Dart, the constructors can also have parameters, such constructors are called parameterized constructor. It is created to initialize the objects with some different values. These parameters will decide which constructor will be called and which will be not. A constructor can have single or multiple parameters. 

Syntax :

class ClassName { 

   ClassName( parameter_list )

  // body of the constructor 

}

Consider the following code in Dart that explains the concept of parameterized constructor

Example : 

 /* A program to illustrate the concept of

* parameterized constructor.

* Consider the definition of the class student */

class student

{

  // parameterized constructor of the class

  student( int a )

  {

          print( ' This is the parameterized constructor ' ) ;

          a = 5 ;

          print( ' Value of a is : ' ) ;

          print( a ) ;

  }

}

void main( )

{

  // Creating an object s1 of the class student

  student s1 = new student( 5 ) ;

}

Output :

 This is the parameterized constructor

Value of a is :

5

Note : You can’t have two constructors with the same name although they have different parameters. The compiler will display an error.

Named Constructor :

As you can’t define multiple constructors with the same name, this type of constructor is the solution to that problem. They allow the user to make multiple constructors with a different name.

Syntax :

class_name.constructor_name ( parameters ) {

   // Body of the Constructor

}

Consider the following code in Dart that explains the concept of named constructor

Example :

/* A program to illustrate the concept of

* named constructor.

* Consider the definition of the class student */




class student

{

   /* creating the named constructor with a single

    * parameter a. Thus, it is a parameterized

    * constructor as well. */

  student.constructor1( int a )

  {

    print( ' This is the parameterized constructor with only one parameter : $a ' ) ;

  }

   

  /* creating the named constructor with two

   * parameters a and b. Thus, it is a parameterized

   * constructor as well. */

  student.constructor2( int a, int b )

  {

    print( ' This is the parameterized constructor with two parameters ' ) ;

    print( ' Value of a + b is ${ a + b } ' ) ;

  }

}

  void main( ) {

  // creating two objects s1 and s2 of class student

  student s1 = new student.constructor1( 5 ) ;

  student s2 = new student.constructor2( 7, 8 ) ;

}

Output :

This is the parameterized constructor with only one parameter : 5

This is the parameterized constructor with two parameters

Value of a + b is 15

Related Topics

Dart Static Members

Static Members in Dart Static members are the members of the class declared using the 'static' keyword. the static members have the following characteristics :  All the objects of the class having...

3 minutes read.

Dart Keywords

Keywords are the reserved words of a programming language, and they have a special meaning that comes defined by the language. These cannot be used as an identifier, and all...

1 minute read.

Dart HTML DOM

All web pages can be viewed as objects and exist within the browser window. We can access a web page using a web browser and it needs to be connected...

3 minutes read.

Dart URIs

The Uri class supports encoding and decoding of strings with the help of functions to be used in URIs ( which may also be known as URLs ). These functions...

6 minutes read.

Dart Future and Stream

Before understanding Future and Stream in Dart, we need first to get familiar with two terms : Synchronous and Asynchronous Programming.  In synchronous programming, a single operation is handled at a...

9 minutes read.

Dart Objects

Apart from the built-in data types, Dart offers some other data types that have a special role to play. One of them is Objects.  Objects Objects are the foundation of the...

3 minutes read.

Dart super keyword

The ' super ' keyword is used to refer to the immediate parent class object of the currently in-use child class. Using this keyword, we can invoke the superclass (...

6 minutes read.

Dart Optional Parameters

Dart functions can have optional parameters with default values. When we create a function, we can specify parameters that calling code can provide; but if the calling code chooses not...

2 minutes read.

Dart Generators

Synchronous Generator Dart Generator is a unique function that allows us to generate price sequences. Generators return values when needed; means that the value is generated if we try to duplicate...

5 minutes read.

Dart Operators Precedence and Associativity

Precedence of operators determines the order in which the operators are evaluated if they are grouped together in a sentence. If two operators share an operand then the one with...

5 minutes read.

Dart Runes and Graphemes

Runes and Graphemes data types in Dart Runes and Graphemes Runes are the special string of Unicode UTF-32 bits that represent the special syntax. Unicode defines a unique numeric value for each...

2 minutes read.

Interfaces in Dart

An interface in Dart refers to the syntax or blueprint that any class must adhere to. It basically defines the array of methods available on the object. It provides the...

3 minutes read.

Dart Logical Operators

Logical operators are the operators that combine two or more conditions, and accordingly return a Boolean value : true or false. Assume the value of variable A is 25 and B...

2 minutes read.

Dart Generics

Dart Generics is similar to Dart collections, which are used to store homogeneous data. As we have discussed in Dart's features, it is a language with types being optional. By default,...

4 minutes read.

Dart Basics

Dart, as earlier mentioned multiple times, is very similar to C, C++ and Java. It is an object-oriented, garbage collecting and class-based programming language. Let’s look further and see what Dart has...

10 minutes read.

Assert in DART

In any programming language, resolving error is the most unwanted and tedious task. At times it becomes very difficult to find the error in the large code. Dart offers an...

3 minutes read.

Dart Object-Oriented Concepts

Dart is a programming language that supports object-oriented programming. It is focused on the objects that are real-world entities and supports all the concepts of OOPS, such as objects, classes,...

4 minutes read.

Dart Loops

Looping refers to repeating or reusing the same lines of code repeatedly until a particular test condition evaluates to true. It is also known as iterating.  It is effectively used when...

4 minutes read.

Dart lists data type

The most important data type in any programming language is an ordered list of elements, an array. Dart lists resemble JavaScript array lists. Example,               var...

7 minutes read.

Dart Classes

Dart is an object – oriented programming language that supports all the object-oriented programming concepts such as classes, objects, inheritance, data abstraction and data encapsulation. A class can be defined as...

8 minutes read.