Java Reference
In-Depth Information
For example, suppose that in the previous
StudentEmployee
example,
Person
is a class with data field
name
and method
toString
. Suppose, too, that
Student
extends
Person
and overrides
toString
to include the year of graduation. Further,
suppose that
Employee
extends
Person
but does not override
toString
; instead, it
declares that it is
final
.
1.
Since
StudentEmployee
inherits the data members from both
Student
and
Employee
, do we get two copies of
name
?
2.
If
StudentEmployee
does not override
toString
, which
toString
method
should be used?
When many classes are involved, the problems are even larger. It appears,
however, that the typical multiple inheritance problems can be traced to con-
flicting implementations or conflicting data fields. As a result, Java does not
allow multiple inheritance of implementations.
However, allowing multiple inheritance for the purposes of type-
compatibility can be very useful, as long as we can ensure that there are
no implementation conflicts.
Returning to our
Shape
example, suppose our hierarchy contains many
shapes such as
Circle
,
Square
,
Ellipse
,
Rectangle
,
Triangle
. Suppose that for
some, but not all of these shapes, we have a
stretch
method, as described in
Section 4.2.2 that lengthens the longest dimension, leaving all others
unchanged. We could reasonably envision that the
stretch
method is written
for
Ellipse
,
Rectangle
, and
Triangle
, but not
Circle
or
Square
. We would like a
method to
stretch
all the shapes in an array:
public static void stretchAll( WhatType [ ] arr, factor )
{
for( WhatType s : arr )
s.stretch( factor );
}
The idea is that
stretchAll
would work for arrays of
Ellipse
, arrays of
Rectangle
, arrays of
Triangle
, or even an array that contained
Ellipses
,
Rectangles
,
and
Triangles
.
For this code to work, we need to decide the type declaration for
WhatType
. One possibility is that
WhatType
can be
Shape
, as long as
Shape
has
an abstract
stretch
method. We could then override
stretch
for each type
of
Shape
, having
Circle
and
Square
throw
UnsupportedOperationExceptions
.
But as we discussed in Section 4.2.2, this solution seems to violate the
notion of an
IS-A
relationship, and moreover, it does not generalize out to
more complicated cases.
Search WWH ::
Custom Search