Java Reference
In-Depth Information
designing hierarchies
4.2
Suppose we have a
Circle
class, and for any non-null
Circle c
,
c.area()
returns the area of
Circle c
. Additionally, suppose we have a
Rectangle
class,
and for any non-null
Rectangle r
,
r.area()
returns the area of
Rectangle r
. Pos-
sibly we have other classes such as
Ellipse
,
Triangle
, and
Square
, all with
area
methods. Suppose we have an array that contains references to these objects,
and we want to compute the total area of all the objects. Since they all have an
area
method for all classes, polymorphism is an attractive option, yielding
code such as the following:
public static double totalArea(
WhatType
[ ] arr )
{
double total = 0.0;
for( int i = 0; i < arr.length; i++ )
if( arr[ i ] != null )
total += arr[ i ].area( );
return total;
}
For this code to work, we need to decide the type declaration for
WhatType
.
None of
Circle
,
Rectangle
, etc., will work, since there is no
IS-A
relationship.
Thus we need to define a type, say
Shape
, such that
Circle
IS-A
Shape
,
Rectangle
IS-A
Shape
, etc. A possible hierarchy is illustrated in Figure 4.10. Additionally,
in order for
arr[i].area()
to make sense,
area
must be a method available
for
Shape
.
figure 4.10
The hierarchy of
shapes used in an
inheritance example
Shape
Circle
Rectangle
Search WWH ::
Custom Search