×

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

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 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 - Control Flow Statements

The control flow statements are used to define the control on the flow of the program. Dart programs are executed in sequential order i.e., the order in which the programming...

1 minute read.

Dart If statement

If statement is used to set the control on the lines of code. Using if statement, block of code is executed only if the expression in the statement returns true....

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

Dart Isolates

Dart successfully supports asynchronous programming which runs our program without any hindrance. This asynchronous programming is used to achieve concurrency. Dart supports concurrent programming with features such as ‘ async-await...

9 minutes read.

Dart Exception Handling

Exception Class – An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught...

4 minutes read.

Dart Symbols

Symbols data type in Dart A symbol is an object that is the representation of an operator or identifier in Dart. These are compile-time constants.  They are used in APIs that refer...

1 minute read.

Dart Equality and Relational Operators

Dart provides the functionality of checking the relationship between the values or values within the variables. These operators return the resultant value as Boolean, i.e., either ‘true’ or ‘false’. Some important points...

3 minutes read.

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 Built-in Data Types

A data type defines the type of value a variable can hold, such as integer, double, or string.  Dart supports two data types:  1. Built-in data types : These are the data...

1 minute read.

Dart Packages

Every programming language has some in-built functions stored inside the header files that makes the task much easier for the programmer. The Dart Packages refer to the compilation of a...

4 minutes read.

Dart Bitwise and Shift Operators

The Bitwise operators are the operators that perform different operations bit by bit on the value of the two operands. List of Bitwise Operators in Dart Sr. Operators Description 1. & ( Binary AND ) It returns...

2 minutes read.

Dart Comments

Comments are the statements that are used to enhance the readability and understandability of the code. The compiler does not execute these lines. It simply ignores these comments when it scans...

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

Sets data type in Dart A set is an unordered collection of items that are unique. Dart infers that sets tale strings as values. Example, var languages = { ‘Dart’ , ‘Flutter’, ‘Python’,...

3 minutes read.

Dart Variables

Variables are used to store the value of a particular data type referred to in the whole program by a name or identifier. They refer to a memory location as...

5 minutes read.

Dart Single-Page Application Architecture

In a single page application architecture, the source code for a single web page loads the entire application. The responsibility of building the user interface and requesting data from the...

2 minutes read.