Dart by Example: Inheritance

  1. /// Abstract classes can't be instantiated,
  2. /// but can contain some implementation.
  3. abstract class Animal {
  4. String name;
  5. Animal(this.name);
  6. String get noise;
  7. }
  8. /// Classes can be extended to share functionality
  9. class Dog extends Animal {
  10. Dog(String name) : super(name);
  11. String get noise => 'bark!';
  12. }
  13. /// Classes can implement other classes if they
  14. /// define all of the fields
  15. class Pikachu implements Animal {
  16. String name = 'Pikachu';
  17. String get noise => 'pika!';
  18. }
  19. void releaseAnimals(Iterable animals) {
  20. animals.forEach((a) => print('${a.name} has been released: ${a.noise}'));
  21. }
  22. main() {
  23. var barry = new Dog('Barry');
  24. var pika = new Pikachu();
  25. releaseAnimals([barry, pika]);
  26. }
  27.  
  1. $ dart inheritance.dart
  2. Barry has been released: bark!
  3. Pikachu has been released: pika!

by @jryanio | source | license