Dart
interface
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.
Exercise 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().
Show example solution
class Runner {
void run() {
print('Running');
}
}
class Athlete implements Runner {
@override
void run() {
print('Athlete running');
}
}
void main() {
var a = Athlete();
a.run();
}
Test yourself
-
Add the implements keyword
class Athlete ____ Runner {
@override
void run() {
print('Athlete running');
}
}
Show answer
class Athlete implements Runner {
@override
void run() {
print('Athlete running');
}
}
-
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
- implements is only used with abstract classes
Show answer
extends inherits and shares members; implements only requires a contract and demands rewriting members — extends shares; implements demands rewriting.
-
Match the interface parts
- implements
- Keyword
- Runner
- Interface
- Athlete
- Implementing class
Next lesson: Summary - Inheritance