Java Reference
In-Depth Information
DESIGNING CLASSES
A basic problem in object-oriented programming is deciding how the classes in your program should relate
to one another. One possibility is to create a hierarchy of classes by deriving classes from a base class that
you have defined and adding methods and data members to specialize the subclasses. The Animal class and
the subclasses derived from it are an example of this. Another possibility is to define a set of classes that are
not hierarchical, but that have data members that are themselves class objects. A Zoo class might well have
objects of types derived from Animal as members, for example. You can have class hierarchies that contain
data members that are class objects — you already have this with the classes derived from Animal because
they have members of type String . The examples so far have been relatively clear-cut as to which approach
to choose, but it is not always so evident. Quite often you have a choice between defining your classes as a
hierarchy and defining classes that have members that are class objects. Which is the best approach to take?
Like almost all questions of this kind, there are no clear-cut answers. If object-oriented programming
were a process that you could specify by a fixed set of rules that you could just follow blindly, you could
get the computer to do it. There are some guidelines though, and some contexts in which the answer may be
more obvious.
Aside from the desirability of reflecting real-world relationships between types of objects, the need to
use polymorphism is a primary reason for using subclasses (or interfaces, as you see shortly). This is the
essence of object-oriented programming. Having a range of related objects that can be treated equivalently
can greatly simplify your programs. You have seen how having various kinds of animals specified by classes
derived from a common base class, Animal , enables us to act on different types of animals as though they
are the same, producing different results depending on what kind of animal is being dealt with, and all this
automatically.
A Classy Example
Many situations involve making judgments about the design of your classes. The way to go may well boil
down to a question of personal preference. Let's try to see how the options look in practice by considering a
simple example. Suppose you want to define a class PolyLine to represent geometric entities that consist of
a number of connected line segments, as illustrated in Figure 6-6 .
FIGURE 6-6
Figure 6-6 shows two polylines, one defined by four points, the other defined by six points.
 
 
Search WWH ::




Custom Search