Java Reference
In-Depth Information
There are ways to connect related objects without using inheritance. Consider the
task of writing a
Circle
class, in which each
Circle
object is specified by a center
point and a radius. It might be tempting to have
Circle
extend
Point
and add the
radius
field. However, this approach is a poor choice because a class is only sup-
posed to capture one abstraction, and a circle simply isn't a point.
A point does make up a fundamental part of the state of each
Circle
object,
though. To capture this relationship in the code, you can have each
Circle
object
hold a
Point
object in a field to represent its center. One object containing another as
state is called a
has-a relationship.
Has-a Relationship
A connection between two objects where one has a field that refers to the
other. The contained object acts as part of the containing object's state.
Has-a relationships are preferred over is-a relationships in cases in which your
class cannot or should not substitute for the other class. As a nonprogramming anal-
ogy, people occasionally need legal services in their lives, but most of them will
choose to
have
a lawyer handle the situation rather than to
be
a lawyer themselves.
The following code presents a potential initial implementation of the
Circle
class:
1 // Represents circular shapes.
2
public class
Circle {
3
private
Point center;
4
private double
radius;
5
6 // constructs a new circle with the given radius
7
public
Circle(Point center,
double
radius) {
8
this
.center = center;
9
this
.radius = radius;
10 }
11
12 // returns the area of this circle
13
public double
getArea() {
14
return
Math.PI * radius * radius;
15 }
16 }
This design presents a
Circle
object as a single clear abstraction and prevents
awkward commingling of
Circle
and
Point
objects.
Search WWH ::
Custom Search