On this page11 sections
Lecture 042: Inheritance
| Day | Extra Topics |
| Lecture | 042 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
A dog is an animal. A manager is an employee. Inheritance lets one class build on another, so the shared parts are written once and every child class gets them for free.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 030–033: classes, objects, constructors and this.
Learning Objectives
- Explain what inheritance is and why it saves code
- Create a child class with
extends - Pass values to the parent constructor with
super - Add new fields and methods to a child class
- Check an object's type with
is
1. The Idea
Without inheritance, a Dog class and a Cat class would both repeat the same name field and
the same eat() method. With inheritance, the shared parts live in one parent class
(Animal), and each child class adds only what is special about it.
| Word | Meaning |
|---|---|
| parent class / superclass | the class being built on (Animal) |
| child class / subclass | the class that builds on it (Dog) |
extends | the keyword that makes a class a child |
2. extends and super
class Animal {
String name;
Animal(this.name);
void eat() {
print('$name is eating.');
}
}
class Dog extends Animal {
Dog(super.name); // hand `name` to Animal's constructor
void bark() {
print('$name says Woof!');
}
}
class Cat extends Animal {
bool indoor;
Cat(super.name, this.indoor); // one value for Animal, one for Cat
void meow() {
print('$name says Meow! (indoor: $indoor)');
}
}super.name in the constructor means "pass this value to the parent's constructor". The child
gets everything the parent has (name, eat()) and adds its own (bark(), indoor, meow()).
void main() {
var dog = Dog('Tommy');
dog.eat(); // inherited from Animal
dog.bark(); // Dog's own
var cat = Cat('Kitty', true);
cat.eat();
cat.meow();
}Output
Tommy is eating.
Tommy says Woof!
Kitty is eating.
Kitty says Meow! (indoor: true)3. "Is-a" and the is Keyword
A Dog is an Animal, so is confirms both. A Cat is not a Dog.
print(dog is Animal); // true
print(dog is Dog); // true
print(cat is Dog); // falseUse inheritance only when the "is-a" sentence makes sense. A car is a vehicle: yes. A car is an engine: no. A car has an engine, so the engine should be a field.
4. One Parent Only
A Dart class can extend one class. But chains are fine: Puppy extends Dog, and
Dog extends Animal, so a Puppy has everything from both.
Code Examples
Example 1: Staff at a Company
class Employee {
final String name;
final double salary;
Employee(this.name, this.salary);
void showInfo() {
print('$name earns Rs $salary');
}
}
class Manager extends Employee {
final int teamSize;
Manager(super.name, super.salary, this.teamSize);
void holdMeeting() {
print('$name holds a meeting with $teamSize people.');
}
}
class Developer extends Employee {
final String language;
Developer(super.name, super.salary, this.language);
void writeCode() {
print('$name writes $language code.');
}
}
void main() {
var m = Manager('Sana', 250000, 6);
var d = Developer('Bilal', 180000, 'Dart');
m.showInfo();
m.holdMeeting();
d.showInfo();
d.writeCode();
}Output
Sana earns Rs 250000.0
Sana holds a meeting with 6 people.
Bilal earns Rs 180000.0
Bilal writes Dart code.showInfo() was written once in Employee, and both Manager and Developer use it.
Common Beginner Mistakes
1. Forgetting to pass values to the parent
class Dog extends Animal {
Dog(String name);
}Error: The implicitly called unnamed constructor from 'Animal' has required parameters.
Try adding an explicit super initializer with the required arguments.Animal needs a name. Write Dog(super.name);
2. Calling a child's method on a parent object
var a = Animal();
a.bark();Error: The method 'bark' isn't defined for the type 'Animal'.Every dog is an animal, but not every animal can bark.
3. Extending two classes
class C extends A, B {}Error: Each class definition can have at most one extends clause.4. Using inheritance for "has-a": class Car extends Engine is wrong. Give Car an
Engine engine; field instead.
Practice Questions
- In
class Laptop extends Computer, which is the parent and which is the child? - What does
super.namedo in a constructor? - Can a class extend two classes in Dart?
class Truck extends Vehicle. IsTruck('Hino') is Vehicletrue or false?- Should
Student extends Schoolbe used? Why or why not?
Practice Answers
Computeris the parent;Laptopis the child.- It passes that value to the parent class's constructor.
- No, only one. Chains (
A extends B,B extends C) are allowed. - True. A truck is a vehicle.
- No. A student is not a school; a school has students. Use a list field instead.
Key Takeaways
- Inheritance puts shared code in a parent class; children reuse it.
class Child extends Parentcreates the relationship.super.fieldin a constructor passes values to the parent.- Children can add their own fields and methods.
- Only one
extendsper class; use it only for true "is-a" relationships.