Sometimes you want to define WHAT a class should do, without specifying HOW it does it. This is where Abstract Classes and Interfaces come in.
1. Abstract Classes
An abstract class cannot be instantiated directly. It is meant to be extended. It can contain methods without a body (abstract methods).
Abstract Definition
1abstract class Animal {2 void eat(); // Abstract method: No body {}3 4 void sleep() {5 print('Zzz...'); // Function with body6 }7}8 9// class Pet = new Animal(); ❌ Error: Abstract classes can't be created.10 11class Dog extends Animal {12 @override13 void eat() {14 print('Dog eats meat'); // MUST implement abstract methods15 }16}HintAbstract classes act as a template. If you extend it, you promise to fill in the blanks (eat).
2. Interfaces (Implements)
Dart does not have an interface keyword. Instead, EVERY class is implicitly an interface. Creating a "pure interface" is creating an abstract class.
Using Implements
1abstract class Swimmer {2 void swim();3}4 5abstract class Flyer {6 void fly();7}8 9// A Duck can swim AND fly. 10// "extends" implies what it IS. "implements" implies what it DOES.11class Duck extends Animal implements Swimmer, Flyer {12 @override13 void eat() => print('Duck eats bread');14 15 @override16 void swim() => print('Duck swims');17 18 @override19 void fly() => print('Duck flies');20}HintYou can implement Multiple interfaces (implements A, B), but only extend One class.
3. Extends vs Implements
The key difference is code reuse versus contract enforcement.
Comparison
1// EXTENDS (Inheritance)2// - You inherit the code (methods have bodies).3// - "Is-A" relationship.4// - Limit: Single parent.5 6// IMPLEMENTS (Interface)7// - You inherit specific method signatures (names), but NO code.8// - You must re-write every single method yourself.9// - Limit: None (Multiple interfaces allowed).HintUse extends when you want to share code. Use implements when you just want to enforce a standard set of methods.
Loot collected
Key takeaways- Abstract classes cannot be instantiated (
new AbstractClass()). - Abstract methods define a method signature but have no body
{}. - Subclasses MUST overlap/implement all abstract methods.
- Every class in Dart is an interface. Use
implementsto force a class to adhere to a contract.
Side quests
Practice exercises
Exercise 1: Database Contract
Define an abstract class Database with methods save() and load().
Reveal solutionHide solution
1abstract class Database { void save(); void load(); }Exercise 2: Implementation
Create a SqlDatabase that implements Database.
Reveal solutionHide solution
1class SqlDatabase implements Database { void save() {...} void load() {...} }