Conversation


Your input fuels progress! Share your tips or experiences on prioritizing mental wellness at work. Let's inspire change together!

Join the discussion and share your insights now!

Comments 0


advertisement

Constructors in Dart Programming

Constructor in Dart


Constructors are special methods that have the same name as a class and are used to initialize an object. Whenever an object is created in a program, it automatically calls the constructor.

Syntax of Constructor:

class Classname{
  classname(){
  }
}



Types of Constructors in Dart

There are three types of constructors which include:

  • Default constructor
  • Parameterized constructor
  • Named constructor.


1. Default constructor:

Default constructors are those constructors that do not have parameters. They are also called not-argument constructors.

void main(){
student std = new student();
}
class student{
 student(){
  print("Default Constructors");
 }
}



2. Parameterized constructor:

Parameterized constructors are those constructors which have parameters through which they take in some variables as arguments. These will help us decide which constructor will be called.

class student{
 student(String name){
   print("Student name is: ${name}");
 }
}
void main(){
student std = new student("John");
}



3. Named constructor:

A named constructor is used to create multiple constructors with different names in the same class.

void main(){
 student std1 = new student();
 student std2 = new student.namedConst("Computer Science");
}
class student{
 student(){
  print("Default constructor");
 }
 student.namedConst(String branch){
  print("Branch name is: ${branch}");
 }
}


The default constructor takes no arguments, whereas, for the named constructor, a string parameter called is passed.

Finally, the print () statement is used to print the branch on the terminal.


Dart Constructor Default Constructor Named Constructor Parameterized constructor

advertisement


Profile Image

Published by: 

1 Follower

Zia

Web Developer | App Developer | Freelancer | Blogger