Reputation: 240
Is there anything wrong with extending a generic class just to simplify or prevent writing redundant code?
Basically what I want to do is
class EnityGroup extends LinkedList<Entity>
{
....
}
but every example I've seen composition seems to be preferred.
What, if any, are the issues, concerns, conflicts etc that I would have to worry about.
Upvotes: 0
Views: 55
Reputation: 133577
What you are looking for is a type alias, a feature available in other programming languages (eg. C or C++). Java doesn't provide such feature.
For the type system EntityGroup
is-a LinkedList<Entity>
so nothing bad can happen. Every method that accepts a LinkedList<Entity>
will accept an EntityGroup
instance.
The only shortcoming is that the constructors are not directly available to your subclass so you are forced to redeclare them (possibly forwarding arguments to superclass constructor).
From a polymorphic point of view this is not like having a type alias, since EntityGroup
is a different type which extends another type, not a different name for LinkedList<Entity>
. So LinkedList.class != EntityGroup.class
, this could create problems with code that uses reflection, unless written correctly to automatically detects types in the hierarchy.
Inheritance is there to enrich or specialize behavior of a class, which is not the case in this situation. You are basically using a feature to obtain something that is not meant to be obtained in this way, but by having type aliases, which unfortunately aren't available in Java.
Upvotes: 1