Dart: Constructor | Default Constructor | Parameterised Constructor

Dart: Constructor | Default Constructor | Parameterised Constructor

·

1 min read

Constructor

  • A Dart constructor has the same name as its class and can be Parameterised. If a class does not define a constructor, Dart implicitly provides a default constructor with no parameters. This default constructor calls the no-argument constructor in the superclass.

  •   class_name( [ parameters ] ){
          // Constructor Body
      }
    
class MyClass {
  // Default constructor
  MyClass() {
    // Initialization code
  }
}

Default Constructor

  • A default constructor is a constructor that doesn't take any parameters. If a class doesn't explicitly define a constructor, Dart implicitly provides a default constructor. This default constructor has no arguments and invokes the superclass's no-argument constructor.
class Car {
  // This is a default constructor
  Car() {
    print('An instance of the Car class is created');
  }
}

void main() {
  var car = new Car(); // An instance of the Car class is created
}

Parameterised Constructor

  • Parameterized constructor is used to initialize the instance variables of the class. Parameterized constructor is the constructor that takes parameters. It is used to pass the values to the constructor at the time of object creation.

Syntax

class ClassName {
  // Instance Variables
  int? number;
  String? name;
  // Parameterized Constructor
  ClassName(this.number, this.name);
}