Abstract Classes, Interfaces and Contracts
Define contracts with abstract classes and interfaces, and use the Liskov substitution principle to check that subclasses honor its parent's promises.
Welcome back!
Step 1 of 13Learn
Classes that exist to be extended
Some classes describe a general idea that should never be instantiated by itself. There's no such thing as "a shape" with no particular form; there are circles and rectangles. An abstract class captures what all subclasses share and declares methods that each subclass must provide.
Java and C# have an abstract keyword. JavaScript doesn't, so developers simulate it:
class Shape {
constructor() {
if (new.target === Shape) throw new Error('Shape is abstract');
}
area() { throw new Error('Subclasses must implement area()'); }
describe() { return 'A shape with area ' + this.area().toFixed(2); }
}
class Circle extends Shape {
constructor(r) { super(); this.r = r; }
area() { return Math.PI * this.r ** 2; }
}The abstract class mixes two kinds of methods:
- Abstract methods such as
area(): declared, not implemented. Each subclass fills them in. - Concrete methods such as
describe(): real code, shared by every subclass, which may call the abstract methods.
This combination is called the template method pattern: the parent fixes the overall algorithm, and subclasses fill in specific steps. Python offers the same through the abc module: inherit from ABC and mark methods with @abstractmethod, and Python refuses to create instances of a class that hasn't implemented them all.
Step 2 of 13Practice · Choose one
Why does the Shape constructor check new.target === Shape?
Step 3 of 13Learn
Interfaces: a contract without code
An interface is a pure contract: a list of methods a class promises to provide, with no implementation and no fields. Java, C#, Kotlin, Swift ("protocols") and TypeScript all support interfaces explicitly:
// TypeScript
interface Exporter {
export(rows: string[][]): string;
}
class CsvExporter implements Exporter {
export(rows: string[][]) { return rows.map(r => r.join(',')).join('
'); }
}A class can implement many interfaces even in languages that allow only one superclass. A Document can be Printable, Serializable and Comparable at once.
Abstract class or interface? A useful rule of thumb:
- Use an interface when unrelated classes need the same capability. A
PdfReportand aPhotocan both bePrintablewithout being related at all. - Use an abstract class when closely related classes share real code and state, such as every
Shapesharingdescribe().
Code that depends on an interface instead of a concrete class is much easier to change. A function that accepts any Exporter works with CSV today and with JSON, Excel or a test double tomorrow, without being edited. This idea, program to an interface, not an implementation, appears again in the design principles module.
Plain JavaScript has no interface keyword; the contract lives in documentation and duck typing, and TypeScript adds compile-time checking.
Step 4 of 13Compare
Abstract class vs. interface
| Aspect | Abstract class | Interface |
|---|---|---|
| Contains code | Yes: concrete methods plus abstract ones | Traditionally no (some languages now allow default methods) |
| Fields and constructor | Yes | No |
| How many a class can use | One parent class (Java, C#, JavaScript) | Many |
| Expresses | An is-a relationship with shared implementation | A can-do capability |
| Example | Shape with shared describe() | Printable, Comparable, Exporter |
Step 5 of 13Learn
The Liskov substitution principle
Inheritance compiles easily. Whether it is correct depends on a rule named after computer scientist Barbara Liskov: objects of a subclass must be usable anywhere the parent is expected, without the program behaving incorrectly. This is the Liskov substitution principle (LSP).
The classic violation is a square that extends a rectangle:
class Rectangle {
setWidth(w) { this.w = w; }
setHeight(h) { this.h = h; }
area() { return this.w * this.h; }
}
class Square extends Rectangle {
setWidth(w) { this.w = w; this.h = w; } // keep sides equal
setHeight(h) { this.w = h; this.h = h; }
}
function stretch(rect) {
rect.setWidth(5);
rect.setHeight(4);
return rect.area(); // any Rectangle should give 20
}stretch(new Rectangle()) returns 20. stretch(new Square()) returns 16, because setting the height also changed the width. Mathematically a square is a rectangle, yet in this code it breaks a promise that rectangles make: width and height can change independently.
LSP violations usually look like one of these:
- an override that throws where the parent worked (
Penguin.fly()throwing); - an override that demands more of its inputs than the parent did;
- an override that delivers less than the parent promised, or breaks the parent's invariants.
The fix is usually a different model: make Square and Rectangle separate immutable shapes, or give birds that can't fly a different interface.
Step 6 of 13Practice · Work it out
Using the code above, what does stretch(new Square()) return?
Step 7 of 13Practice · Chart
stretch() promises 20 for any Rectangle
Which call breaks the parent's promise?
Tap the bar that answers the question, then press Check.
Step 8 of 13Practice · Select all that apply
Which of these subclasses violate the Liskov substitution principle? Select all that apply.
Select all that apply.
Step 9 of 13Note
Step 10 of 13Learn
Design by contract
Every public method makes a promise, whether or not anyone writes it down. Making that promise explicit is called design by contract, and it has three parts:
- Preconditions: what must be true before the method is called.
withdraw(amount)requires a positive amount. - Postconditions: what the method guarantees afterwards. After a successful withdrawal, the balance has dropped by exactly
amount. - Invariants: what is always true about the object between calls. The balance is never negative.
These three ideas give the Liskov substitution principle a precise form. A subclass may weaken preconditions (accept more inputs than the parent) and strengthen postconditions (promise more), but it must never demand more or deliver less, and it must keep the parent's invariants. A PremiumAccount that allows an overdraft up to $500 changes the invariant "balance is never negative", so it can surprise code written for Account; that relationship needs careful thought.
Interfaces in typed languages capture only the method names and types. The rest of the contract lives in documentation and tests. A good habit is to write down preconditions and postconditions in a short comment for every public method of an interface or abstract class.
Step 11 of 13Practice · Sort into groups
Classify each part of the contract for a method removeItem(id) on a shopping cart.
Tap an item, then tap its group (or drag it there).
Step 12 of 13Diagram
A method's contract, before and after
Tap a shape with to see more.
- Preconditions
The caller's duty: a positive amount, an existing item.
- Method runs
- Postconditions
The method's promise: balance dropped by exactly amount.
Step 13 of 13Practice · Fill in the blanks
Fill in the blanks
A class that cannot be instantiated and may contain both implemented and unimplemented methods is an class. A pure list of methods that a class promises to provide, with no fields, is an . The rule that a subclass must work anywhere its parent is expected is the Liskov principle.
Lesson complete!