Explain it simply
Inheritance in plain language
Inheritance lets a new class start from an existing one. The new class, called the subclass, automatically gets every field and method of the parent (the superclass), and then adds its own or changes some of them. You write what every Employee has once, and Engineer and Manager only say how they differ.
The test that tells you it is the right tool is the sentence 'a Manager is an Employee'. If that kind of sentence sounds wrong ('a Car is an Engine'), you are looking at a has-a relationship, and the other object belongs in a field instead.
Problem → Why → Solution
The problem: classes grown by copy and paste
A payroll tool starts with an Engineer class, and a few weeks later a Manager appears. Manager needs the same name and base salary, so the fields and the describe method are copied across. When a rule changes, say the report format, every copy has to be edited by hand.
Worse, the type system sees no connection between the two classes. A function that takes a List<Engineer> rejects a Manager, so code that should handle any employee has to be written twice or loosened to dynamic.
class Engineer {
Engineer(this.name, this.baseSalary);
final String name;
final double baseSalary;
String describe() => '$name earns $baseSalary';
}
class Manager {
Manager(this.name, this.baseSalary, this.reports);
final String name;
final double baseSalary;
final int reports;
String describe() => '$name earns ${baseSalary + reports * 150}';
}
void printAll(List<Engineer> people) {
for (final p in people) {
print(p.describe());
}
}
void main() {
// Error: 'Manager' can't be assigned to a variable of type 'Engineer'.
printAll([Engineer('Mia', 4200), Manager('Joe', 4400, 4)]);
}Copying gives you no shared type
Copying duplicates behaviour, but it cannot tell the compiler that two classes belong together. Inheritance does both jobs: the shared code lives in one place, and Manager becomes a subtype of Employee, so one List<Employee> can hold both and each element still runs its own version of monthlyPay.
Core concept: extends, super, @override and abstract
A subclass is declared with extends: class Manager extends Employee { ... }. It inherits every instance field, getter, setter and method of the superclass, and the compiler accepts a Manager anywhere an Employee is expected. Dart has single inheritance, so a class has exactly one superclass; reuse beyond that comes from mixins (next lesson) and interfaces. A class without an extends clause extends Object, which is why every value has toString, == and hashCode.
Constructors are the one thing that is not inherited. A subclass constructor must make the superclass constructor run, because the parent's fields have to be set before the child uses them. Write the call in the initializer list, Savings(String owner, this.rate) : super(owner), or use super-parameters, Savings(super.owner, this.rate), which forward the argument by name and position. If you write nothing, Dart implicitly calls the superclass's unnamed zero-argument constructor, and the code does not compile when there is none.
To change inherited behaviour, declare a method with the same name and mark it @override. The annotation is optional for the compiler, but it makes your intent checkable: the analyzer warns when the name matches nothing above you. Inside the override, super.describe() runs the parent's version, so you extend it instead of replacing it. An override must keep a compatible signature: parameter types the same or wider, the return type the same or narrower.
An abstract class, written abstract class Employee, cannot be instantiated and may declare abstract methods with no body. It is a contract with some shared code attached: each concrete subclass must supply the missing members or the compiler rejects it. A variable typed as the abstract class can hold any subclass instance, and a call such as employee.monthlyPay() runs the version belonging to the object's real class. That is polymorphism, and it is what lets one loop handle every kind of employee.
| What a subclass gets | Detail |
|---|---|
| Instance fields, getters, setters, methods | Inherited, and can be overridden |
| Constructors | Not inherited; each class declares its own and chains to super |
| Static members | Not inherited; call them on the declaring class |
| Names starting with _ | Private to the library (file), not to the class |
- Parent holds the shared fields and code
- Child extends it and adds what is new
- @override swaps one method's body
- super.x() still reaches the parent's body
- Calls run the object's real class
The variable's type decides which members you may call; the object's real class decides which body runs.
General pattern
abstract class Parent {
Parent(this.field);
final Type field;
Result requiredMember(); // abstract: no body
Result sharedMember() => /* inherited as is */;
}
class Child extends Parent {
Child(super.field, this.extra);
final Type extra;
@override
Result requiredMember() => /* this class's version */;
}The parent holds the shared fields and concrete methods and declares the rest as abstract members. The child forwards arguments with super-parameters, adds its own fields and overrides what it must.
Worked example: payroll with Engineer and Manager
Employee holds what every employee shares and declares the one thing that differs, monthlyPay, as abstract. Engineer pays the base salary; Manager adds a bonus per report and extends describe by calling super. The loop at the bottom never asks which kind of employee it has.
Class hierarchy
---------------
Object
|
Employee (abstract)
name, baseSalary, describe()
monthlyPay() <- no body
/ \
Engineer Manager
monthlyPay() monthlyPay() + reports * 150
describe() = super + extraabstract class Employee {
Employee(this.name, this.baseSalary);
final String name;
final double baseSalary;
// Abstract: no body here, every concrete subclass must supply one.
double monthlyPay();
String describe() => '$name earns ${monthlyPay().toStringAsFixed(2)}';
}
class Engineer extends Employee {
Engineer(super.name, super.baseSalary);
@override
double monthlyPay() => baseSalary;
}
class Manager extends Employee {
Manager(super.name, super.baseSalary, this.reports);
final int reports;
@override
double monthlyPay() => baseSalary + reports * 150;
@override
String describe() => '${super.describe()} (manages $reports people)';
}
void main() {
final staff = <Employee>[
Engineer('Mia', 4200),
Manager('Joe', 4400, 4),
];
for (final person in staff) {
print(person.describe());
}
final total = staff.fold<double>(0, (sum, e) => sum + e.monthlyPay());
print('Payroll: ${total.toStringAsFixed(2)}');
}Code breakdown
- Abstract member
double monthlyPay();A method that ends in ; with no body is abstract. Every concrete class that extends Employee must write its own monthlyPay.
- Super-parameters
Engineer(super.name, super.baseSalary);super.name and super.baseSalary forward the two arguments straight to the Employee constructor. Engineer adds no fields, so it needs no body.
- Extra field
Manager(super.name, super.baseSalary, this.reports);Manager forwards two super-parameters to the parent and sets its own field with this.reports. It does not redeclare the parent's fields, because it already inherited them.
- Override and extend
String describe() => '${super.describe()} (manages $reports people)';Manager overrides describe but calls super.describe() first and appends text. When Employee's format changes, Manager follows automatically.
- Polymorphic loop
print(person.describe());person is typed as Employee, but at run time an Engineer uses Engineer's monthlyPay and a Manager uses Manager's.
Mia earns 4200.00
Joe earns 5000.00 (manages 4 people)
Payroll: 9200.00Construction order and the overridable-call trap
When a child object is built, the order is fixed: first the child's field initializers and initializer list, then the superclass constructor (including its body), and only at the end the child constructor's body. The code below prints each step so you can watch it.
class Base {
Base(String label) {
print('2. Base body ($label)');
announce(); // calls the CHILD's override
}
void announce() => print(' Base.announce');
}
class Child extends Base {
final String tag = _log('1. Child field initializer');
String? ready;
Child(String label)
: super(_log('1b. argument for super: $label')) {
ready = 'set';
print('3. Child body, ready=$ready');
}
@override
void announce() => print(' Child.announce, ready=$ready');
}
String _log(String message) {
print(message);
return message;
}
void main() {
Child('demo');
}1. Child field initializer
1b. argument for super: demo
2. Base body (1b. argument for super: demo)
Child.announce, ready=null
3. Child body, ready=setNotice the trap: when the Base constructor calls announce(), Dart runs the child's override, but the child body has not started, so ready is still null. Avoid calling overridable methods from a constructor; if you must, remember that the subclass's state is not complete yet.
Choosing between extends, implements and composition
There are three ways to reuse a class, and they give you different things. extends hands you the bodies, implements hands you only the shape (the list of members) and no bodies, and composition builds no class relationship at all: you simply hold another object in a field.
| Tool | You get | Use it when |
|---|---|---|
| extends | All fields and method bodies | It is a real is-a and you want to share code |
| implements | Only the member list, no bodies | Many classes must meet a contract in their own way |
| Composition (a field) | Only the right to call its public methods | It is a has-a, or you may swap the behaviour later |
class Logger {
String prefix = '[log]';
void log(String message) => print('$prefix $message');
}
// extends: inherits the field and the method body.
class FileLogger extends Logger {}
// implements: inherits NOTHING, only the shape. Everything is rewritten.
class SilentLogger implements Logger {
@override
String prefix = '';
@override
void log(String message) {}
}
void main() {
final loggers = <Logger>[FileLogger(), SilentLogger()];
for (final l in loggers) {
l.log('started');
}
print(loggers[1] is Logger);
}This prints [log] started once, then true. FileLogger prints because it inherited the body; SilentLogger prints nothing because implements made it write its own log(), yet it can still be used wherever a Logger is expected. If you implement a class and skip a member, the compiler reports 'missing implementations for these members'.
class Logger {
void log(String message) => print('[log] $message');
}
class OrderService {
OrderService(this._logger);
final Logger _logger; // has-a, not is-a
void place(String item) {
_logger.log('order placed: $item');
}
}
void main() {
OrderService(Logger()).place('keyboard');
}OrderService is not a Logger; it uses one. If you later want a different logging implementation, you change the constructor argument and OrderService's public API is untouched.
Dart 3 class modifiers: what they forbid outside the library
Dart 3 lets you put a modifier in front of a class declaration to control what other code may do with it. A library is, in the simple case, one Dart file. The restrictions apply to other libraries that import it; inside the declaring library you can still extend and implement.
| Modifier | Outside its library | Why use it |
|---|---|---|
| abstract | Cannot construct; extend and implement allowed | A shared contract with optional shared code |
| base | Extend allowed, implement forbidden | Every subtype must inherit your constructor logic |
| interface | Implement allowed, extend forbidden | You expose a contract but not your implementation |
| final | Neither extend nor implement | A closed class you can change freely |
| sealed | Cannot construct, extend or implement | A closed set of subtypes for exhaustive switch |
Modifiers combine: abstract interface class is the Dart 3 way to say a pure interface. A subtype of a base or final class must itself be base, final or sealed, and that rule applies even inside one library. The errors below were reproduced with two files.
// vehicles.dart
base class Engine {
void start() => print('start');
}
final class Config {
const Config();
}
abstract interface class Repo {
void save();
}// main.dart
import 'vehicles.dart';
class Fake implements Engine {} // error: base class, cannot implement
class Fork extends Config {} // error: final class, cannot extend
base class Car extends Engine {} // fine: a subtype of base says base
class Store implements Repo { // fine: abstract interface class
@override
void save() => print('saved');
}The compiler says 'The class 'Engine' can't be implemented outside of its library because it's a base class.' and 'The class 'Config' can't be extended outside of its library because it's a final class.' When you hit an error like that on a class from someone else's package, read its modifier first. It is also why you write implements Exception rather than extends Exception: in dart:core, Exception is an interface class.
In real projects
Where inheritance shows up in real projects
Flutter widgets run on inheritance: extending StatelessWidget and overriding build is something you do every day. The framework treats every widget as a Widget and calls each one's own build. An abstract class plus overrides is the standard shape of a framework extension point.
- Error types: class ValidationError implements Exception is a custom error with its own message, and callers can catch it precisely with on ValidationError.
- Repository and service layers: an abstract interface class UserRepository is implemented once by a database version for production and once by an in-memory version for tests, and the rest of the code sees only the interface.
- Plugin and strategy designs: for varying parts such as payment providers, an abstract base class owns the workflow and each subclass overrides only the step that differs.
Common mistakes
Common mistakes with inheritance
Extending only to reuse code when it is not an is-a
Writing class Invoice extends Customer just to read customer.name means an Invoice can now be passed wherever a Customer is expected, which makes no sense. A final Customer customer; field inside Invoice is the honest design.
Forgetting to call the super constructor
If Account has only Account(this.owner) and you write Savings(String owner, this.rate);, you get 'The implicitly called unnamed constructor from 'Account' has required parameters.' (reproduced). Fix it with Savings(super.owner, this.rate);.
A mismatched override signature, or a typo that @override would have caught
Overriding Animal.speak(String sound) with void speak(int times) fails with 'The parameter 'times' of the method 'Dog.speak' has type 'int', which does not match the corresponding type, 'String', in the overridden method, 'Animal.speak'.' A misspelled name such as spek, on the other hand, compiles: it is a new method and never replaces the parent's method, so dart run still prints the parent's behaviour. With @override in place the analyzer flags the name that matches nothing.
Calling a subclass-only method through a superclass type
After User u = Admin();, calling u.deletePost() fails with 'The method 'deletePost' isn't defined for the type 'User'.' (reproduced), because the variable's type decides which members you may call. Check the type first (u is Admin) so Dart promotes it.
Best practices
Best practices
- Say the is-a sentence out loud; if it sounds wrong, choose composition.
- Keep hierarchies shallow, two or three levels, because each level makes a reader hunt one step further for the real code.
- Add @override on every override so a rename or a typo cannot pass silently.
- On a library's public classes, state your intent with a modifier: final if nobody should subclass it, abstract interface class for a pure contract.
Mini challenge
Mini challenge: a shape hierarchy
Write an abstract class and two subclasses for different shapes. Shape stores a name, declares area() as abstract and uses both in describe(). Circle and Rectangle supply their own area(), and Rectangle also extends describe().
- Shape is abstract, stores a name, declares double area() as abstract and implements describe()
- Circle and Rectangle extend Shape and pass their name up with super
- Rectangle overrides describe(), calls super.describe() and appends its size
- Put both in a List<Shape> and print each description plus the total area
import 'dart:math' as math;
// TODO 1: make Shape abstract; store a name and declare `double area();`
class Shape {
// TODO: constructor, name field, abstract area(), concrete describe()
}
// TODO 2: Circle extends Shape (radius field, pass 'circle' to super)
// TODO 3: Rectangle extends Shape (width, height; override area() and describe())
void main() {
// TODO 4: put a Circle(2) and a Rectangle(3, 4) in a List<Shape>
// TODO 5: print every describe() and then the total area (2 decimals)
}Expected: Running it should print: circle with area 12.57 rectangle with area 12.00 (3.0x4.0) Total area: 24.57
Show hint
Pass the name with an initializer list: Circle(this.radius) : super('circle');. Calling area() inside Shape.describe() runs the real class's version, so describe can live in Shape. Use fold<double> for the total; math.pi comes from dart:math.
Show solution
import 'dart:math' as math;
abstract class Shape {
Shape(this.name);
final String name;
double area();
String describe() => '$name with area ${area().toStringAsFixed(2)}';
}
class Circle extends Shape {
Circle(this.radius) : super('circle');
final double radius;
@override
double area() => math.pi * radius * radius;
}
class Rectangle extends Shape {
Rectangle(this.width, this.height) : super('rectangle');
final double width;
final double height;
@override
double area() => width * height;
@override
String describe() => '${super.describe()} (${width}x$height)';
}
void main() {
final shapes = <Shape>[Circle(2), Rectangle(3, 4)];
for (final s in shapes) {
print(s.describe());
}
final total = shapes.fold<double>(0, (sum, s) => sum + s.area());
print('Total area: ${total.toStringAsFixed(2)}');
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- With extends a subclass gets the parent's fields and methods but not its constructors; call the parent constructor with super(...) or super-parameters.
- @override replaces a method, while super.method() calls the parent's version so you can extend it.
- An abstract class cannot be instantiated and its abstract members force every subclass to fill them in, which is the basis of polymorphism.
- Use composition when it is not an is-a and implements for a pure contract; base, interface, final and sealed restrict what other libraries may do.
Dart language overview — Dart