Back to quest
Object Oriented ProgrammingLevel 28 / 32

Inheritance & Super

Understand the "Is-A" relationship, how to extend classes, and how to use the `super` keyword.

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

example.dart
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 Animal
14class Dog extends Animal {
15 // Constructor must call super
16 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 Animal
26 d.bark(); // Specific to Dog
27}

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

example.dart
1class Bird extends Animal {
2
3 Bird(String name) : super(name);
4
5 @override
6 void eat() {
7 super.eat(); // Run the parent's generic eat logic first
8 print('...pecking seeds'); // Then add specific logic
9 }
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

example.dart
1// Hierarchy: Object -> Animal -> Mammal -> Dog
2class 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 extends to create a subclass (Child).
  • Use super to access the parent class.
  • Inheritance models an "Is-A" relationship.
  • A class can only execute one parent class.

Side quests

Practice exercises

1

Exercise 1: Shape Class

Create a Shape class with a color field, and a Circle class that extends it adding a radius.

Reveal solution
solution.dart
1class Shape { String color; Shape(this.color); } class Circle extends Shape { double r; Circle(String c, this.r) : super(c); }
2

Exercise 2: Override

Override toString() in your Circle class to print its color and radius.

Reveal solution
solution.dart
1@override String toString() => 'Circle $color $radius';
Party chat

Comments