Joona I Palaste said:
I have done some thinking about this. Yes, it's nice to inherit from
HashMap to avoid typing the methods yourself, but that's really all it
buys you. Inheritance should be a "is-a" relationship. For example,
animals are lifeforms, mammals are animals, dogs are mammals, and
dalmatians are dogs. Each subclass uses *all* the functionality of its
superclass.
Generally, when people want to make their own Map, they extend
HashMap and override a few methods. This ties the internal
implementation of the mapping algorithm to HashMap. The author
of the new Map usually doesn't need this, he/she doesn't even need
to know or care what the algorithm is. As far as the new Map
implementation goes, the mapping algorithm works by magic.
What if some other mapping algorithm works better in some
circumstances?
You would need to make a new subclass, which would be totally
incompatible with the original subclass. With aggregation, you only
need to make one class, which implements the Map interface, but
only implements the new features, and leaves the basic Map stuff
to an already existing Map implementation class.
You, and others, make valid points, and I would generally agree with what
is
being discussed / recommended. However, you are all assuming, I think,
that
any inheritance is performed at the top level:
public class MyHashMap extends HashMap ...
In Java, as you probably all know, it is possible to, very easily, use
both
inheritance and composition / aggregation [I'll use the term 'containment'
here] by implementing local classes or inner classes.
To return to the earlier example, MyHashMap could be implemented to use a
HashMap subclass via containment; the subclass would be implemented as an
inner class, and relevant MyHashMap methods would delegate to the relevant
subclass instance methods.
Using this, albeit contrived, approach, you've been able to subclass
HashMap, whilst at the same time having quarantined the HashMap subclasses
within MyHashMap, thus haven't 'polluted' the HashMap hierarchy.
Cheers,
Anthony Borla
P.S.
I'm not advocating the above design approach merely highlighting it as a
possibility.
P.P.S.
In UML there actually *is* a difference between aggregation and
composition
having to do with whether contained entities are an integral part of the
containing entity. Please refer to:
http://www.softdocwiz.com/UML.htm
for more details on these definitions.