Dart DOES NOT support multiple parent class. It can only extend from ONE parent class
So we create base class Anima. It uses a named required parameter. The brackets mean it is named, so when
others put in params, they are forced to put in the name age first. The required means this function must take in this parameter.
1 2 3 4 5 6 7 8 9 |
class Animal { Animal({required this.age}) { print('√ Constructing Animal object with $this.age'); } final int age; void sleep() => print('sleep'); } |
Since Animal has named param age, we must specify age in super()
Let’s use named param to better describe what the other constructor params mean:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Dog extends Animal { String type = ""; String? name; Dog({required int age, required String type, String? name}) : super(age: age) { print('√ Constructing a $type Dog that is $age years old'); this.type = type; this.name = name ?? "no name given"; } void bark() => print('bark'); } |
Now we see that the child class Dog can sleep, which is derived from its parent.
It can also bark, which is its own functionality.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import 'Dog.dart'; void main() { final d = Dog(age: 2, type: 'Doberman'); // √ Constructing Animal object with Instance of 'Dog'.age // √ Constructing a Doberman Dog that is 2 years old d.bark(); // bark d.sleep(); // sleep print(d.name); // no name given print(d.type); // Doberman } |
So it tells us that it goes into the parent class first. Creates the instance, and then comes back down to the child to construct.