Last active
October 11, 2019 20:41
-
-
Save kirkdrichardson/030764a47bc7599b0e1853bda75c7639 to your computer and use it in GitHub Desktop.
Basic inheritance and polymorphism in Dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Basic inheritance and polymorphism in Dart (as of v2.5) | |
// see https://dartpad.dartlang.org/030764a47bc7599b0e1853bda75c7639 | |
void main() { | |
print(''); | |
print('------------------ Tree object, Tree Reference ----------------------'); | |
print(''); | |
final Tree t = Tree(); | |
t.grow(); | |
print(''); | |
print('------------------ ChristmasTree object, Tree Reference ----------------------'); | |
print(''); | |
final Tree ct = ChristmasTree(); | |
ct.grow(); | |
// Expect error - Though this is a ChristmasTree object, BUT it is a Tree reference. | |
// i.e., the holdOrnaments() method is not seen. | |
// ct.holdOrnaments(); | |
print(''); | |
print('------------------ ChristmasTree object, ChristmasTree Reference ----------------------'); | |
print(''); | |
final ChristmasTree christmasTree = ChristmasTree(); | |
christmasTree.holdOrnaments(); | |
// Notice here too, that even though our "ct" variable is a Tree reference, | |
// The Tree object has leafType as a field, and since it is visible, we use the overriden | |
// version (i.e. we see "Needle" rather than "General") | |
print(""" | |
A christmas tree has leaves of type "${christmasTree.leafType}" | |
Really! They have "${ct.leafType}" type of leaves! | |
But... Most trees have "${t.leafType}" types of leaves. | |
"""); | |
} | |
class Plant { | |
String leafType = "General"; | |
Plant() { | |
print('Created a plant!'); | |
} | |
void grow() { | |
print('Growing plantly.'); | |
} | |
} | |
class Tree extends Plant { | |
Tree() { | |
print('Created a tree!'); | |
} | |
// Overrides the grow method of the parent. | |
void grow() { | |
// Call to grow method of the parent class via super keyword. | |
super.grow(); | |
print('Growing tree-like'); | |
} | |
} | |
class ChristmasTree extends Tree { | |
String leafType = "Needle"; | |
ChristmasTree() { | |
print('Created a Christmas tree!'); | |
} | |
void grow() { | |
print('Growing ChristmasTree-like'); | |
} | |
void holdOrnaments() { | |
print('Only a Christmas tree can hold ornaments!'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment