Inheritance allows a class to inherit fields and methods from another class. This promotes code reuse ("Don't Repeat Yourself").
1. What is Inheritance? (Extends)
If you have multiple classes with similar code (e.g., Dog, Cat, Bird all have logic to move/eat), you can pull that common code into a parent Animal class.
Parent and Child
1// Parent Class (Superclass)2class Animal {3 String name;4 5 Animal(this.name);6 7 void eat() {8 print('$name is eating');9 }10}11 12// Child Class (Subclass)13// Dog IS-A Animal14class Dog extends Animal {15 // Constructor must call super16 Dog(String name) : super(name);17 18 void bark() {19 print('Woof!');20 }21}22 23void main() {24 var d = Dog('Rex');25 d.eat(); // Inherited from Animal26 d.bark(); // Specific to Dog27}HintThe Dog class gets name and eat() for free without re-typing them.
2. The `super` Keyword
super refers to the parent class. You use it to call the parent's constructor or methods.
Calling Super Logic
1class Bird extends Animal {2 3 Bird(String name) : super(name);4 5 @override6 void eat() {7 super.eat(); // Run the parent's generic eat logic first8 print('...pecking seeds'); // Then add specific logic9 }10}11 12// Result of bird.eat():13// "Tweety is eating"14// "...pecking seeds"HintOverriding methods allows you to customize inherited behavior.
3. Single Inheritance
In Dart, a class can only extend ONE parent class. You cannot say class Dog extends Animal, Pet.
The Hierarchy
1// Hierarchy: Object -> Animal -> Mammal -> Dog2class Mammal extends Animal {3 Mammal(String name) : super(name);4}5 6class Dog extends Mammal {7 Dog(String name) : super(name);8}9// This works, but keep hierarchies shallow to avoid confusion.HintIf you need to share code across unrelated classes, use Mixins (next lesson) instead of Inheritance.
Loot collected
Key takeaways- Use
extendsto create a subclass (Child). - Use
superto access the parent class. - Inheritance models an "Is-A" relationship.
- A class can only execute one parent class.
Side quests
Practice exercises
Exercise 1: Shape Class
Create a Shape class with a color field, and a Circle class that extends it adding a radius.
Reveal solutionHide solution
1class Shape { String color; Shape(this.color); } class Circle extends Shape { double r; Circle(String c, this.r) : super(c); }Exercise 2: Override
Override toString() in your Circle class to print its color and radius.
Reveal solutionHide solution
1@override String toString() => 'Circle $color $radius';