Java Reference
In-Depth Information
SUBCLASS, ABSTRACT CLASS, OR INTERFACE?
There is usually more than one way to solve a problem. Some problems can be solved by sub-
classing, by use of abstract classes, or by interfaces. The following general guidelines may help:
▪
Use an abstract class
when you want to provide a template for a series of subclasses, all of
which may inherit some of their functionality from the parent class but are required to imple-
ment some of it themselves. (Any subclass of a geometric
Shapes
class might have to provide
a
computeArea()
method; because the top-level
Shapes
class cannot do this, it would be ab-
stract. This is implemented in
Polymorphism/Abstract Methods
.
)
▪
Subclass
when you need to extend a class and add some functionality to it, whether the parent
class is abstract or not. See the standard Java APIs and the examples in Recipes , , , , and oth-
ers throughout this topic.
▪
Subclass
when you are required to extend a given class. Some APIs such as
servlets
use sub-
classing to ensure “base” functionality in classes that are dynamically loaded (see
Loading
▪
Define an interface
when there is no common parent class with the desired functionality and
when you want only certain unrelated classes to have that functionality (see the
Power-
Switchable
interface in
Providing Callbacks via Interfaces
)
. You should also choose this op-
tion if you know that you'll need (or think there is even a chance you might later need) to be
able to pass in unrelated classes for testing purposes. “Mock object” is a very common
strategy in unit testing. Some say that interfaces should be your first choice at least as often as
subclassing.
▪
Use interfaces as “markers”
to indicate something about a class. The standard API, for ex-
Suppose we are generating a building management system. To be energy efficient, we want
to be able to remotely turn off (at night and on weekends) such things as room lights and
computer monitors, which use a lot of energy. Assume we have some kind of “remote con-
trol” technology. It could be a commercial version of BSR's house-light control technology
X10, it could be Bluetooth or 802.11—it doesn't matter. What matters is that we have to be
very careful what we turn off. It would cause great ire if we turned off computer processors
automatically—people often leave things running overnight. It would be a matter of public
safety if we ever turned off the building emergency lighting.
[
30
]
So we've come up with the design shown in
Figure 8-1
.