What is Inheritance?
Inheritance lets a class (child/subclass) inherit all the fields and methods of another class (parent/superclass). The child class can then add its own members or override inherited ones. This promotes code reuse and establishes an "is-a" relationship.
extends Keyword
class Animal {
String name;
Animal(this.name);
void eat() => print('$name is eating.');
void breathe() => print('$name is breathing.');
}
class Dog extends Animal {
String breed;
Dog(String name, this.breed) : super(name);
void bark() => print('$name says: Woof!');
}
class Cat extends Animal {
Cat(String name) : super(name);
void meow() => print('$name says: Meow!');
}
super Keyword
super refers to the parent class. Use it to call the parent constructor or access parent methods:
Dog rex = Dog('Rex', 'German Shepherd');
rex.eat(); // Rex is eating. (inherited from Animal)
rex.breathe(); // Rex is breathing. (inherited)
rex.bark(); // Rex says: Woof! (Dog's own method)
Overriding Methods
A subclass can redefine a parent method using @override:
class Animal {
String name;
Animal(this.name);
void speak() => print('$name makes a sound.');
}
class Dog extends Animal {
Dog(String name) : super(name);
@override
void speak() => print('$name says: Woof!');
}
class Cat extends Animal {
Cat(String name) : super(name);
@override
void speak() => print('$name says: Meow!');
}
Full Example
class Shape {
String color;
Shape(this.color);
double area() => 0;
void describe() => print('A $color shape with area $${area().toStringAsFixed(2)}');
}
class Circle extends Shape {
double radius;
Circle(String color, this.radius) : super(color);
@override
double area() => 3.14159 * radius * radius;
}
class Rectangle extends Shape {
double width, height;
Rectangle(String color, this.width, this.height) : super(color);
@override
double area() => width * height;
}
void main() {
var shapes = [
Circle('red', 5),
Rectangle('blue', 4, 6),
];
for (var s in shapes) {
s.describe();
}
}
Output:A red shape with area 78.54
A blue shape with area 24.00
💪 Exercise
- Create a
Vehicle parent class and Car, Truck, Motorcycle subclasses.
- Override a
fuelType() method in each subclass.
- Create a list of mixed Vehicle types and call
fuelType() on each.
🧠 Quiz
1. Which keyword is used to inherit from a parent class in Dart?
- A) implements
- B) inherits
- C) extends ✅
- D) from
2. What does @override mean?
- A) Hides the parent method
- B) Signals that a method intentionally replaces the parent version ✅
- C) Deletes the parent method
- D) Calls the parent method
Summary
Inheritance uses extends to create a child class that reuses parent fields and methods. Use super() to call the parent constructor. Override methods with @override to customize behavior in subclasses. Dart supports single inheritance only (one parent per class).