Dart
Summary - Classes
Combine named, const and factory constructors to write a Point class.
Summary - Classes
In this group you saw four constructor kinds: default, named, const and factory. We will merge them in a single Point class.
A Point class may hold a const Point(this.x, this.y) default constructor, a const Point.origin() : x = 0, y = 0 named constructor and a factory Point.fromList(list) factory constructor. Each offers a different init scenario; the class is one, the init paths are many. In the last step we will write and call all three.
Exercise Add named + const to Point
Define the Point class; add final double x and final double y fields. Write the const Point(this.x, this.y) default constructor. Add the const Point.origin() : x = 0, y = 0 named constructor. In main, create an instance with const p = Point.origin(); and call print(p.x) and print(p.y).
Show example solution
// Define the Point class
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin() : x = 0, y = 0;
}
void main() {
const p = Point.origin();
print(p.x);
print(p.y);
}
Add a factory to Point
In the third step we add a factory constructor to the Point class. This factory builds an instance from a list: factory Point.fromList(List<double> list) { return Point(list[0], list[1]); }.
Now the caller can create instances directly with Point(3, 4), a zero point with Point.origin() and from a list with Point.fromList([3, 4]). Three constructor kinds sit side by side on the same class, each serving a different use case. The factory body requires a return.
Exercise Add the fromList factory to Point
Keep the existing Point class (final x, final y, const Point and const Point.origin). Add a factory Point.fromList(List<double> list) { return Point(list[0], list[1]); } factory constructor to the class. In main, create an instance with var q = Point.fromList([3, 4]); and call print(q.x) and print(q.y).
Show example solution
class Point {
final double x;
final double y;
const Point(this.x, this.y);
const Point.origin() : x = 0, y = 0;
factory Point.fromList(List<double> list) {
return Point(list[0], list[1]);
}
}
void main() {
var q = Point.fromList([3, 4]);
print(q.x);
print(q.y);
}
Test yourself
-
Which constructor fits caching?
Show answer
factory — A factory can return an existing instance, so it fits the cache pattern.
Next lesson: extends