Interfaces and Abstract Classes
Define a contract with an interface, share partial code with an abstract class, and see how Java and C++ express each.
Two tools for one job
Both let you write code against an idea ("something you can pay with") instead of a concrete class.
- Interface: a contract. It lists method signatures and says nothing about how they work. Any class that signs the contract can be used wherever the interface is expected.
- Abstract class: a half-finished class. It can hold fields and finished methods, plus some abstract methods (declared but not written) that subclasses must fill in. You cannot create an object of it directly.
| Interface | Abstract class | |
|---|---|---|
| Holds fields (state) | No instance fields | Yes |
| Holds finished methods | Only default / static ones in Java | Yes |
| A class can use how many | Many | One parent only (Java) |
| Best for | A capability or role ("can be paid with") | Shared code for a family of related classes |
| In C++ | A class with only pure virtual methods | A class with some pure virtual methods |
C++ has no interface keyword. A pure virtual method (virtual void f() = 0;) has no body in the base, and a class with at least one is abstract. An "interface" in C++ is simply an abstract class with nothing but pure virtual methods and a virtual destructor.
Quick check
1 / 2
You need ten unrelated classes (Invoice, Report, Image) to all be printable. Which fits better?
2 / 2
Five kinds of report share the same loading and formatting code and differ only in one calculation. Which fits better?
1 of 5