Java Reference
In-Depth Information
2.
Abstract methods
. Overriding is resolved at run time. The base class
provides no implementation and is abstract. The absence of a default
requires either that the derived classes provide an implementation or
that the classes themselves be abstract.
3.
Static methods
. Overridding is resolved at compile time because there
is no controlling object.
4.
Other methods
. Overriding is resolved at run time. The base class
provides a default implementation that may be either overridden by
the derived classes or accepted unchanged by the derived classes.
4.2.2
designing for the future
Consider the following implementation for the
Square
class:
public class Square extends Rectangle
{
public Square( double side )
{ super( side, side ); }
}
Since obviously a square is a rectangle whose length and width are the
same, it would seem reasonable to have
Square
extend
Rectangle
, and thus
avoid rewriting methods such as
area
and
perimeter
. While it is true that
because
toString
is not overridden,
Squares
will always be output as
Rectangles
with identical lengths and widths, that can be repaired by providing a
toString
method for
Square
. Thus the
Square
class can be made slick and we can reuse
Rectangle
code. But is this a reasonable design? To answer that question, we
must go back to the fundamental rule of inheritance.
The
extends
clause is appropriate only if it is true that
Square
IS-A
Rectangle
.
From a programming perspective, this does not simply mean that a square
must geometrically be a type of rectangle; rather, it means that any operation
that a
Rectangle
can perform must also be able to be supported by a
Square
.
Most important, however, this is not a static decision, meaning that we do not
simply look at the current set of operations supported by
Rectangle
. Rather,
we must ask if it is reasonable to assume that in the future it is possible that
operations might be added to the
Rectangle
class that would not make
sense for a
Square
. If that is the case, then the argument that a
Square
IS-A
Rectangle
is weakened considerably. For instance, suppose the
Rectangle
class
has a
stretch
method whose contract provides that
stretch
lengths the larger
dimension of the
Rectangle
, while leaving the smaller dimension in tact.
Clearly the operation cannot be made available to a
Square
, since doing so
would destroy squareness.
Search WWH ::
Custom Search