Java Reference
In-Depth Information
C OMMON E RROR 10.1: Confusing Super- and Subclasses
If you compare an object of type SavingsAccount with an object of type
BankAccount , then you find that
ȗ The keyword extends suggests that the SavingsAccount object is an
extended version of a BankAccount .
ȗ The SavingsAccount object is larger; it has an added instance field
interestRate .
ȗ The SavingsAccount object is more capable; it has an addInterest
method.
It seems a superior object in every way. So why is SavingsAccount called the
subclass and BankAccount the superclass?
The super/sub terminology comes from set theory. Look at the set of all bank
accounts. Not all of them are SavingsAccount objects; some of them are other
kinds of bank accounts. Therefore, the set of SavingsAccount objects is a
subset of the set of all BankAccount objects, and the set of BankAccount
objects is a superset of the set of SavingsAccount objects. The more
specialized objects in the subset have a richer state and more capabilities.
442
443
10.2 Inheritance Hierarchies
In the real world, you often categorize concepts into hierarchies. Hierarchies are
frequently represented as trees, with the most general concepts at the root of the
hierarchy and more specialized ones towards the branches. Figure 3 shows a typical
example.
In Java it is equally common to group classes in complex inheritance hierarchies.
The classes representing the most general concepts are near the root, more specialized
classes towards the branches. For example, Figure 4 shows part of the hierarchy of
Swing user interface components in Java.
Sets of classes can form complex inheritance hierarchies.
Search WWH ::




Custom Search