interface
- Dart course
- Intermediate
- Lesson 11/116
- 5 min
Learn to implement interfaces with implements.
implements
In Dart every class also serves as an interface. To re-implement all members of a class, use the implements keyword.
Example: class Athlete implements Runner { @override void run() { print('Athlete running'); } }. Here Athlete implements the Runner interface. implements does not inherit; it only requires a contract. All methods and fields of Runner are rewritten inside Athlete. Multiple interfaces can be listed with commas: implements Runner, Swimmer.
Multiple interfaces
Dart uses single inheritance; extends targets only one class. By contrast implements can apply many interfaces at once, separated by commas.
Example: class Triathlete implements Runner, Swimmer, Cyclist { ... }. Every method of all three interfaces is rewritten inside Triathlete. This shape is the Dart recommended path when multiple inheritance is wanted. It can also be combined with extends: class Triathlete extends Person implements Runner, Swimmer. Order matters: extends first, then implements.
Practice Write Athlete with implements
Keep the existing Runner class. Define a class named Athlete that implements the Runner interface; add an @override void run() { print('Athlete running'); } method. In main, create an instance with var a = Athlete(); and call a.run().
Starter code
class Runner {
void run() {
print('Running');
}
}
// Define Athlete implementing the Runner interface
void main() {
// Create an Athlete() instance and call run()
}Sample solution
class Runner {
void run() {
print('Running');
}
}
class Athlete implements Runner {
@override
void run() {
print('Athlete running');
}
}
void main() {
var a = Athlete();
a.run();
}Expected output
Athlete running
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add the implements keyword
class Athlete ____ Runner {
@override
void run() {
print('Athlete running');
}
}
class Athlete implements Runner {
@override
void run() {
print('Athlete running');
}
}
Explanation: implements is used to apply a class as an interface.
2 What is the difference between extends and implements?
- extends copies code, implements shares it
- They are exactly the same
- extends inherits and shares members; implements only requires a contract and demands rewriting members Correct answer
- implements is only used with abstract classes
Explanation: extends shares; implements demands rewriting.
3 Match the interface parts
| Term | Meaning |
|---|---|
implements |
Keyword |
Runner |
Interface |
Athlete |
Implementing class |