CodeBlanks Logo Icon CodeBlanks

Named constructors

Learn multiple constructors with named constructors.

Named constructors

A named constructor adds a dot and a name to the class name: Point.origin(). This shape offers different initialization forms for the same class; overloading in Dart works this way.

Example: class Point { double x, y; Point(this.x, this.y); Point.origin() : x = 0, y = 0; }. Here Point.origin() takes no parameters and sets both fields to zero. The call is Point.origin(); the default constructor Point(3, 4) sits beside it. You may write as many named constructors per class as you need.

Multiple named constructors

Multiple named constructors can sit side by side on the same class. Each offers a different initialization scenario; whichever name the call uses, that one runs.

Example: a Temperature class may start from Celsius or Fahrenheit: Temperature.celsius(this.c) and Temperature.fahrenheit(double f) : c = (f - 32) * 5 / 9. The caller picks the constructor that matches the unit they hold. If no default constructor is needed, it can be omitted; named constructors alone can build the class.

Practice Add the Point.origin() constructor

Keep the existing Point class. Add a Point.origin() : x = 0, y = 0; named constructor to the class. In main, create an instance with var p = Point.origin(); and print the x field with print(p.x).

Starter code

main.dart
class Point {
  double x, y;
  Point(this.x, this.y);
  // Add the Point.origin() named constructor
}

void main() {
  // Create a Point.origin() instance and print p.x
}

Sample solution

main.dart
class Point {
  double x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
}

void main() {
  var p = Point.origin();
  print(p.x);
}

Expected output

0.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the named constructor name

Question
class Point {
  double x, y;
  Point(this.x, this.y);
  Point.____() : x = 0, y = 0;
}
Answer
class Point {
  double x, y;
  Point(this.x, this.y);
  Point.origin() : x = 0, y = 0;
}

Explanation: A named constructor name starts with a lowercase letter and follows the dot.

2 When is Point.origin() used?

  • To delete any instance of the class
  • To do a special, parameterless init for the (0, 0) point Correct answer
  • To replace the default constructor
  • To make the class abstract

Explanation: Point.origin() offers a special init; with no parameters it sets the fields to zero.

3 Match the named constructor parts

Term Meaning
Point Class name
origin Constructor name
: x = 0, y = 0 Initializer list

All lessons in Intermediate