Pattern: Abstract Class

Intent

Decide whether to create an abstract class.

Context

If one class is a specialisation of another (that is, it implements extra representation and/or behaviour), then it can be implemented as a subclass. However, there are occasions when two classes are both specialisations of a common base.

Solution

If two classes are each a specialisation of a common base, then this common base can be implemented as an abstract class. An abstract class defines the common representation and/or behaviour of its concrete subclasses.

In addition to defining the behaviour common to its subclasses, an abstract class will define protocol which is common to, but implementated by, the concrete subclasses. These methods in the abstract class serve as documentation holder. They contain a comment and a #subclassResponsibility message send.

Abstract classes are never instantiated.

Example

Imagine two new classes: CurrentAccount and SavingsAccount with the following attributes:

CurrentAccount (number, balance, cheques)
SavingsAccount (number, balance, interestRate)

The number and balance attributes are common to both classes. We can create an abstract class BankAccount to implement these common attributes (and their corresponding methods), and subclass SavingsAccount and CurrentAccount from it.

BankAccount (number, balance)
SavingsAccount (interestRate)
CurrentAccount (cheques)

Known Uses

The Boolean class is an abstract class with two concrete subclasses: True and False. The Boolean class implements behaviour common to True and False (#asBoolean, #deepCopy etc). It also defines the protocol which is common to True and False but which will be implemented by them (#and:, #ifTrue: etc).

Related Patterns