Let's start building our own custom types in Dart:
- First, define a class called Name, which is an object that stores a person's first and last names:
class Name {
final String first;
final String last;
Name(this.first, this.last);
@override
String toString() {
return '$first $last';
}
}
- Now, let's define a subclass called OfficialName. This will be just like the Name class, but it will also have a title:
class OfficialName extends Name {
// Private properties begin with an underscore
final String _title;
// You can add colons after constructor
// to parse data or delegate to super
OfficialName(this._title, String first, String last)
: super(first, last);
@override
String toString() {
return '$_title. ${super.toString()}';
}
}
- Now, we can see all these concepts in action by using the playground method:
void classPlayground() {
final name = OfficialName('Mr', 'Francois', 'Rabelais');
final message = name.toString();
print(message);
}
- Finally, add a call to classPlayground in the main method:
main() {
...
classPlayground();
}