Multiple Interfaces
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 48 of 110.
One of the biggest advantages of interfaces over inheritance is that a class can implement multiple interfaces. While Dart restricts you to extending only one class, you can implement as many interfaces as you need.
abstract class Printable {
void printContent();
}
abstract class Saveable {
void save();
}
abstract class Shareable {
void share(String recipient);
}
class Document implements Printable, Saveable, Shareable {
String content;
Document(this.content);
@override
void printContent() {
print('Printing: $content');
}
@override
void save() {
print('Saving document...');
}
@override
void share(String recipient) {
print('Sharing with $recipient');
}
}When implementing multiple interfaces, you must provide implementations for all methods from every interface. The class must fulfill all contracts it promises to support.
You can also combine extends with multiple implements:
class Report extends Document implements Printable, Shareable {
Report(String content) : super(content);
// Must still implement all interface methods
// (already inherited from Document in this case)
}This flexibility lets you design classes that fit multiple roles. A SmartPhone could implement Camera, Phone, and MusicPlayer interfaces, promising it can do everything each interface requires while keeping its own unique implementation.
Challenge
EasyLet's build a smart device system that demonstrates how a single class can implement multiple interfaces to combine different capabilities. You'll create separate interface classes for different device features, then build a device that can do it all.
You'll organize your code into two files:
devices.dart: Define your interfaces and the implementing class here:- A
Connectableclass with a methodconnect()that printsConnecting to network... - A
Chargeableclass with a methodcharge()that printsCharging battery... - A
Displayableclass with a methodshowScreen(String content)that printsDisplaying: [content] - A
Tabletclass that implements all three interfaces:Connectable,Chargeable, andDisplayable. Add aString brandproperty with a constructor. Your implementations should print[brand] tablet connecting to WiFifor connect,[brand] tablet charging via USB-Cfor charge, and[brand] screen: [content]for showScreen
- A
main.dart: Import your devices file and demonstrate how the Tablet fulfills all three interface contracts:- Create a
Tabletwith brand'Galaxy' - Call
connect() - Call
charge() - Call
showScreen('Welcome Home')
- Create a
Your Tablet class must provide its own implementation for every method from all three interfaces. This shows how implementing multiple interfaces lets a single class promise multiple capabilities while keeping each implementation unique to the device.
Expected output:
Galaxy tablet connecting to WiFi
Galaxy tablet charging via USB-C
Galaxy screen: Welcome HomeCheat sheet
A class can implement multiple interfaces by listing them after the implements keyword, separated by commas:
abstract class Printable {
void printContent();
}
abstract class Saveable {
void save();
}
class Document implements Printable, Saveable {
@override
void printContent() {
print('Printing...');
}
@override
void save() {
print('Saving...');
}
}When implementing multiple interfaces, you must provide implementations for all methods from every interface.
You can combine extends with multiple implements:
class Report extends Document implements Printable, Shareable {
Report(String content) : super(content);
// Must implement all interface methods
}This allows a class to fulfill multiple contracts and fit multiple roles simultaneously.
Try it yourself
import 'devices.dart';
void main() {
// TODO: Create a Tablet with brand 'Galaxy'
// TODO: Call connect()
// TODO: Call charge()
// TODO: Call showScreen('Welcome Home')
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor