Java Reference
In-Depth Information
Like all questions of this kind, there are no clear-cut answers. If object-oriented programming was a
process that we could specify by a fixed set of rules that you could just follow blindly, we 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 we shall 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 allows us to act on different types of
animal 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 we want to define a class PolyLine to represent lines
consisting of one or more connected segments, as illustrated in the diagram:
P
P
P
P
P
P
P
P
P
P
X-Axis
This shows two polylines, one defined by four points, the other defined by seven points.
It seems reasonable to represent points as objects of a class Point . Points are well-defined objects that
will occur in the context of all kinds of geometric entities. We have seen a class for points earlier that we
put in the package Geometry . Rather than repeat the whole thing, we will define the bare bones we
need in this context:
public class Point {
// Create a point from its coordinates
public Point(double xVal, double yVal) {
x = xVal;
y = yVal;
}
// Create a point from another point
Search WWH ::




Custom Search