Re: Inheritance versus Composition
Oliver Wong wrote:
"Lew" <lew@nospam.lewscanon.com> wrote in message
news:ENqdnR8Km7lYNmXYnZ2dnUVZ_syunZ2d@comcast.com...
Use inheritance to model "is-a": Derived is-a Base.
In other words, when the derived object /is/ a base object, like a
Circle is-a Shape.
I use the "is-a" trick as a guideline too, but it's only a guideline;
not a hard and fast rule -- and geometry is one of the places where the
guideline fails. According to geometry, a square is-a rectangle, so
anywhere you can use a rectangle, you could use a square, right? Not if
the rectangle class defines a setSize(height, width) method, which doesn't
make too much sense for a square.
....
java.util.Properties is a good example of over-application of is-A. It
extends Hashtable, as far as I can tell just because it was implemented
as a Hashtable.
That leads to gems such as the following quote from the API
documentation: "Because Properties inherits from Hashtable, the put and
putAll methods can be applied to a Properties object. Their use is
strongly discouraged as they allow the caller to insert entries whose
keys or values are not Strings. The setProperty method should be used
instead."
It would have been much better designed with a Hashtable reference as a
private field.
I would strengthen "is-a" to something like "class X logically must have
all attributes and operations of class Y, for all time, regardless of
future additions to Y".
A LinkedHashMap must be able to do everything a HashMap can do, and will
go on doing so even if new features are added to HashMap. LinkedHashMap
extends HashMap makes sense.
Patricia