×

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 Installation Guide

There are various ways of compiling and running an application created in Dart, either by compiling the Dart code to JavaScript using the Dart2js tool or by running on the...

3 minutes read.

Dart Features

Dart is a fully-featured, object-oriented modern language with its roots in the programming language ‘Smalltalk’. It has some of its eminent features similar to the languages such as Java, C#...

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.

Rust vs Dart

Rust is a system-level programming language that stands next to C ++ in terms of syntax, but offers greater speed and memory security. Dart, on the other hand, is an...

2 minutes read.

Dart Type inference

The task of interpreting the data types of fields, methods, local variables and most generic type arguments is handled by the static analyser. However, when not enough information is provided...

5 minutes read.

Dart If-else-if statement

If - else - if statement enables to check the set of test expressions that evaluate to Boolean True or False, and based on this true or false the particular...

2 minutes read.

Dart Standard Input & Output

Standard Input in Dart (stdin): The standard input stream reads data both synchronously and asynchronously from the keyboard.  In Dart programming language, .readLineSync( ) function is used to accept input from the...

3 minutes read.

Dart Constants

Dart Constants are the objects or variables whose values can’t change or modify during the execution of the program. Their use case is when we want a particular value to...

2 minutes read.

Dart Miscellaneous types

Some Other Data types in Dart Apart from the data types studied so far, we have three other data types also which are as follows: NeverDynamicVoid Let us understand each one in detail, Never...

3 minutes read.

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...

4 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 Basic Program

Dart provides various convenient platforms to code and compile the program in Dart language. Some of them are: 1. Using IDE = Visual Studio code is a text editor with IDE....

3 minutes read.

Dart Strings

Strings data type in Dart A Dart string is a sequence of characters with an encoding of UTF-16. The text associated with string data type is enclosed withing single (‘  ’)...

3 minutes read.

Dart this Keyword

The ' this ' keyword, similar to that in Java and C#, refers to an object of the class using it. It points to the current object of the class,...

5 minutes read.

Metadata in Dart

Metadata is often referred to as the data about the data. It is a  piece of data about a basic piece of data. In the case of a Dart program,...

2 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 Function

A Dart function is a collective line of code that are targeted to perform a specialised task. Such lines of code (function) can be reused whenever we need to perform...

6 minutes read.

Dart Switch Case Statement

In the case of if-else statements, we prefer not to use the if-else ladder when there are many test conditions to be evaluated. In such a situation, it is preferable...

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.

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.