Skip to content

Instantly share code, notes, and snippets.

@kirkdrichardson
Last active October 11, 2019 23:52
Show Gist options
  • Save kirkdrichardson/19a8c3c203f27fd1820c004582480ff5 to your computer and use it in GitHub Desktop.
Save kirkdrichardson/19a8c3c203f27fd1820c004582480ff5 to your computer and use it in GitHub Desktop.
Interfaces in Dart
// Interfaces in Dart (as of v2.5)
// See live at https://dartpad.dartlang.org/19a8c3c203f27fd1820c004582480ff5
/*
* TLDR;
* There is no interface keyword in Dart. Instead we use a regular class with either the extends or
* implements keyword. If a subclass uses the extends keyword, the child class inherits from the
* parent class normally. Else, if the subclass uses the implements keyword, the parent class is
* treated as an interface: all inherited members must be overriden.
*
* */
void main() {
// We use the methods inheritted from the parent, with the OPTION to override, as normal.
NeutralParent regularChild = RegularChild();
regularChild.doSomethingCool();
print('Favorite color is ${regularChild.favoriteColor}');
print('---------------------------------------');
// Inheriting from in
NeutralParent interfaceBasedChild = InterfaceBasedChild();
interfaceBasedChild.doSomethingCool();
print('Favorite color is ${interfaceBasedChild.favoriteColor}');
}
class NeutralParent {
String favoriteColor = 'Green';
void doSomethingCool() {
print('Wow! Very, very cool!');
}
}
// Normal inheritance
class RegularChild extends NeutralParent {
String favoriteColor = 'NOT Green';
}
// Using the interface keyword here, forces our NeutralParent to behave like an interface
// In this case, we MUST provide concrete implemntations of all class members.
class InterfaceBasedChild implements NeutralParent {
String favoriteColor = 'Mandatorily Pink';
void doSomethingCool() {
print('It isn\'t as cool the second time :`(');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment