0

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.

ydobonebi
  • 240
  • 2
  • 11
  • Where is this paranoid coming from? – SwiftMango Jul 24 '15 at 03:45
  • @texasbruce I've seen this pattern many times, but it is always composition being used. I even found some text books and even they use composition over inheritance (at least when using generics). I think it's silly, but Java isn't my best language so I figure something I don't know might bite my in the ass. – ydobonebi Jul 24 '15 at 03:47
  • Guess it depends on your use case. Check [this](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – logee Jul 24 '15 at 03:47

1 Answers1

1

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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • For the most part, I am thinking about a type alias (with a few added functions to special handling). I just thought this technique made most sense but I never see it done....so I was curious. Really the only argument I've heard against inheritance is that in my case its not a pure is-a relationship only mostly. – ydobonebi Jul 24 '15 at 03:54