Notes
The problem
A first attempt puts everything in one abstract base class: every item has loan days and can be reserved. Then the library adds magazines that never leave the reading room. The magazine class is forced to throw unsupported operation for half its methods, and any code that lends items has to remember which ones blow up. The base class mixed what an item is with what an item can do.
abstract class FatItem {
abstract int loanDays();
abstract void reserve(String member);
}
class Magazine extends FatItem {
int loanDays() {
throw new UnsupportedOperationException();
}
void reserve(String m) { throw ... }
} The idea
Here is the short version. An abstract class is a partly built parent for one family of classes. It shares fields and code, and children extend it. An interface is a capability that any class can sign up for, a contract with no instance state. Every library item has an id, a title and a shelf, so that is the family. Being lendable or reservable are capabilities, so those become interfaces.
- abstract class = a partly
- built parent for one family:
- shared fields and code
- interface = a capability any
- class can sign up for:
- a contract, no instance state
- is-a family vs can-do
The structure
Now every item extends the abstract library item class, which holds the shared parts. A book also implements both Borrowable and Reservable. An ebook implements only Borrowable. A magazine implements neither, so it has no methods it must fake. A class can extend only one class, but it can implement as many interfaces as it needs. Each capability is opted into, never forced.
abstract class LibraryItem { .. }
interface Borrowable { .. }
interface Reservable { .. }
class Book extends LibraryItem
implements Borrowable, Reservable
class Ebook extends LibraryItem
implements Borrowable
class Magazine extends LibraryItem Abstract class holds
An abstract class can hold instance fields, like the id and title. It can have constructors that validate them once for every child. It can mix finished methods, like label, with abstract ones, like shelf, that each child must fill in. Its members can be private, protected or package private. You cannot create it with new, but its constructor still runs as part of creating each child.
private final String id, title;
protected LibraryItem(String id,
String title) {
// validate once, for every item
}
final String label() {
return shelf() + " / " + title;
}
abstract String shelf(); Interface holds
An interface holds abstract methods, here loan days and daily fine. Since Java eight it can also hold default methods with a body, like late fee, which every implementer gets for free and may override. It can have static methods, and since Java nine private helper methods. Its only fields are public static final constants. It has no constructor and no instance state of its own.
int loanDays();
long dailyFine();
default long lateFee(int daysLate) {
return Math.max(0, daysLate)
* dailyFine();
}
static Borrowable none() { .. }
// fields: only public static final Run-through
The loan desk only knows Borrowable. It never mentions books or ebooks. When a book comes back three days late, the default late fee multiplies three days by five rupees and gives fifteen. The ebook overrides late fee to return zero, because it simply expires on the reader. Magazines cannot even be passed to the desk, so the compiler blocks the mistake that used to throw at runtime.
Default method clash
Default methods bring one catch. If Borrowable and Reservable both have a default method called rules with the same signature, a book that implements both will not compile until it overrides rules itself. Inside the override it can call either version with the interface name, dot super, dot rules. Here the book simply joins both. Note that a method inherited from a class always wins over an interface default.
interface Borrowable {
default String rules() {..} }
interface Reservable {
default String rules() {..} }
class Book ... {
@Override public String rules() {
return Borrowable.super.rules()
+ "; " + Reservable.super.rules();
}
} Side by side
Side by side. An abstract class can have instance state and constructors, an interface cannot. A class can implement many interfaces but extend only one class. Both can contain method bodies now, through defaults in interfaces. Interface methods are public, apart from private helpers, while an abstract class can use any access level. Neither can be created with new. Only an interface with a single abstract method can be a lambda target.
- iface abstract
- state no yes
- constructor no yes
- how many many one
- method body default yes
- access public* any
- * private helpers allowed
- both: cannot use new
- lambdas: functional iface
How to choose
A simple rule. First write the contract as an interface, because callers should depend on that. If several implementations repeat the same fields and code, add an abstract base class that implements the interface and holds the shared part. If a class needs to play two roles, use interfaces for the roles, because it can only have one parent class. When in doubt, start with the interface.
- 1 the contract: interface
- (callers depend on this)
- 2 several implementations
- repeat the same code and
- state? add an abstract
- base that implements it
- 3 one class needs two roles?
- interfaces, not classes
- default to the interface
Interface + skeleton
The Java collections use both together. List is the interface everyone codes against, and AbstractList is an abstract class that implements most of List on top of a few methods, so writing your own list takes very little code. The same pairing exists for Set, Map and Collection. Small capabilities, like Comparable and Runnable, are plain interfaces with no skeleton class at all.
- List AbstractList
- Set AbstractSet
- Map AbstractMap
- Collection AbstractCollection
- callers use the interface;
- implementers may extend the
- abstract class to write less
- Comparable, Runnable: pure
- capabilities, no skeleton
Abuse to avoid
Some misuses to avoid. An interface that only holds constants, implemented just to avoid writing a class name, leaks those constants into every implementer. Default methods are meant to add behaviour without breaking existing implementers, not to fake state with static maps. Huge interfaces force classes to implement methods they do not need. And an abstract class with no shared code is just an interface with fewer freedoms.
- • constant interfaces: an
- interface only to hold
- constants (use a class)
- • defaults that fake state
- with static maps
- • huge interfaces with 20
- methods (split them)
- • abstract class with no
- shared code (use interface)
In interviews
In an interview, do not just recite the differences. Explain the choice. Borrowable and Reservable are interfaces, because they are capabilities and a book needs both. Library item is an abstract class, because every item shares an id, a title and the validation in its constructor. The loan desk depends only on Borrowable. That answer shows you understand why, not just what.
- "Borrowable and Reservable
- are interfaces: they are
- capabilities and a Book
- needs both. LibraryItem is
- abstract: every item shares
- id, title and validation.
- The desk depends only on
- Borrowable."