Classes, Enums, Extensions
Abstract Classes and Interface Contracts
abstract class declares a type with abstract members that concrete classes must implement. A function that takes the abstract type works on any concrete implementer; that is polymorphic dispatch. Any class can be used as an interface with implements, which forces the implementer to re-declare every member.
Program
Play the program to dispatch a describe call through the abstract Shape type.
abstract_interface.dart
Replay: real traced execution (multi-file project)
abstract class Shape {
String get name;
int area();
}
class Square implements Shape {
final int side;
Square(this.side);
@override
String get name => 'square';
@override
int area() => side * side;
}
void describe(Shape s) {
print('${s.name} area=${s.area()}');
}
void main() {
Shape s = Square(4);
describe(s);
}
call ← Square(4)
19void main() {20 Shape s = Square(4);21 describe(s);values this stepSquare(4)callSquare built ← side=4
7final int side;8Square(this.side);9@overridevalues this stepside=4Square built4this.sides ← Square(side: 4) as Shape
19void main() {20 Shape s = Square(4);21 describe(s);values this stepSquare(side: 4) as Shapescall ← describe(s)
20 Shape s = Square(4);21 describe(s);22}values this stepdescribe(s)callSquare instancescalls ← s.name, s.area()
15void describe(Shape s) {16 print('${s.name} area=${s.area()}');17}values this steps.name, s.area()callsSquare instancesreturn value ← square
9@override10String get name => 'square';11@overridevalues this stepsquarereturn valuereturn value ← 16
11 @override12 int area() => side * side;13}values this step16return value4sideprint('${s.name} area=${s.area()}');
15void describe(Shape s) {16 print('${s.name} area=${s.area()}');17}outputsquare area=16
abstract class
`abstract class Shape` declares a type that cannot be instantiated directly.
abstract member
`String get name;` and `int area();` end with `;` and no body, so implementers must provide one.
polymorphic dispatch
`describe(Shape s)` accepts any `Shape`; calling `s.name` and `s.area()` runs the concrete `Square` implementation.