extends
- Dart course
- Intermediate
- Lesson 7/116
- 5 min
Learn to inherit from a base class with extends.
extends
In Dart a class inherits from another with the extends keyword. The class being inherited is the base class; the inheriting one is the derived class.
Example: class Dog extends Animal { ... }. Here Dog inherits all public members of Animal. The subclass can call the superclass methods on itself and add new methods or fields. Dart uses single inheritance: each class extends at most one class. To combine behavior from many sources you use mixins, which we will see later.
Inherited methods
A subclass can use the methods of its base class without redefining them. The call goes through its own instance and is automatically routed to the base class.
Example: suppose Animal has void breathe() { print('Breathing'); }. After Dog extends Animal, Dog instances can call breathe() directly: Dog().breathe(). No extra code is needed in the subclass. This reduces duplication: shared behavior lives in the base class and subclasses share it.
Practice Define Dog with extends
Keep the existing Animal class. Define a class named Dog that inherits from Animal; add a Dog(); constructor. In main, create an instance with var d = Dog(); and call d.breathe().
Starter code
class Animal {
void breathe() {
print('Breathing');
}
}
// Define Dog inheriting from Animal
void main() {
// Create a Dog() instance and call breathe()
}Sample solution
class Animal {
void breathe() {
print('Breathing');
}
}
class Dog extends Animal {
Dog();
}
void main() {
var d = Dog();
d.breathe();
}Expected output
Breathing
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid extends declaration?
- class Dog inherits Animal { }
- class Dog implements Animal { }
- class Dog extends Animal { } Correct answer
- class Dog : Animal { }
Explanation: extends is the Dart keyword for inheritance.
2 Add the extends keyword
class Dog ____ Animal {
Dog();
}
class Dog extends Animal {
Dog();
}
Explanation: extends makes the subclass inherit from the base class.
3 Match the inheritance parts
| Term | Meaning |
|---|---|
Animal |
Base class |
Dog |
Derived class |
breathe |
Inherited method |