Site icon TestingDocs.com

Types of Constructors

Overview

Let’s learn about the types of constructors supported by the Dart programming language.

Types of constructors

There are different types of constructors in the Dart language. They are as follows:

Default Constructor

A constructor with no parameters is known as a default constructor or no-argument constructor. If not declared in the class, the Dart compiler will automatically generate it.

Example

// default constructor
Book() {
    title = “Default Title”;
    author = “Default Author”;
    price = 0.0;
}

To create an object for the class:

Book bObj = new Book();

Parameterized Constructor

By using parameterized constructors, you can define constructors that include parameters. These parameters are utilized to initialize instance variables when an object is created.

Example

// parameterized constructor
Book(String t, String a, double p) {
       title = t;
       author = a;
       price = p;
}

To create an object using the parameterized constructor:

Book bObj = new Book(“University Physics”,”Sears & Zemansky”,99.99);

 

Named Constructor

Named constructors are additional constructors that are given a name and can be used to create objects with different configurations. The named constructors are used to declare the multiple constructors in the class.

The general syntax for named constructor is as follows:

className.named_constructor(parameters);

Example

Declaring a named constructor for the Book class.

// named constructor
Book.FreeBook(String title,String author) {
      this.title=title;
     this.author=author;
     price=0.0;
}

We can create the object using the named constructor:

Book bObj = new Book.FreeBook(“Free Dart Tutorial”, “TestingDocs Team”);

Dart Tutorials

Dart tutorial on this website can be found at:

https://www.testingdocs.com/dart-tutorials-for-beginners/

More information on Dart:

https://dart.dev/

Exit mobile version