Dart
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.
Exercise 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).
Show example solution
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);
}
Test yourself
-
Complete the named constructor name
class Point {
double x, y;
Point(this.x, this.y);
Point.____() : x = 0, y = 0;
}
Show answer
class Point {
double x, y;
Point(this.x, this.y);
Point.origin() : x = 0, y = 0;
}
-
When is Point.origin() used?
- To delete any instance of the class
- To do a special, parameterless init for the (0, 0) point
- To replace the default constructor
- To make the class abstract
Show answer
To do a special, parameterless init for the (0, 0) point — Point.origin() offers a special init; with no parameters it sets the fields to zero.
-
Match the named constructor parts
- Point
- Class name
- origin
- Constructor name
- : x = 0, y = 0
- Initializer list
Next lesson: Initializer list