Java Reference
In-Depth Information
figure 4.11
A possible
Shape
class
1
public class Shape
2
{
3
public double area( )
4
{
5
return -1;
6
}
7
}
This suggests a class for
Shape
, as shown in Figure 4.11. Once we have the
Shape
class, we can provide others, as shown in Figure 4.12. These classes
also include a
perimeter
method.
The code in Figure 4.12, with classes that extend the simple
Shape
class in
Figure 4.11 that returns -1 for
area
, can now be used polymorphically, as
shown in Figure 4.13.
A huge benefit of this design is that we can add a new class to the hierar-
chy without disturbing implementations. For instance, suppose we want to
add triangles into the mix. All we need to do is have
Triangle
extend
Shape
,
override
area
appropriately, and now
Triangle
objects can be included in any
Shape[]
object. Observe that this involves the following:
Too many
instanceof
opera-
tors is a symptom
of poor object-
oriented design.
NO CHANGES to the
Shape
class
n
NO CHANGES to the
Circle
,
Rectangle
, or other existing classes
n
NO CHANGES to the
totalArea
method
n
making it difficult to break existing code in the process of adding new code. Notice
also the lack of any
instanceof
tests, which is typical of good polymorphic code.
4.2.1
abstract methods and classes
Although the code in the previous example works, improvements are possi-
ble in the
Shape
class written in Figure 4.11. Notice that the
Shape
class itself,
and the
area
method in particular, are
placeholders
: The
Shape
's
area
method
is never intended to be called directly. It is there so that the compiler and
run-time system can conspire to use dynamic dispatch and call an appropriate
area
method. In fact, examining
main
, we see that
Shape
objects themselves
are not supposed to be created either. The class exists simply as a common
superclass for the others.
5
5.
Declaring a private
Shape
constructor DOES NOT solve the second problem: The constructor
is needed by the subclasses.
Search WWH ::
Custom Search