Search code examples
javalistsubclasssuperclass

Referring to any of the subclasses of a particular superclass in Java


Ok guys, here's a simple question that I couldn't quite manage to figure out on my own. Any help is greatly appreciated!

  • Let's say I have an abstract class Superclass, from which I derived subclasses Subclass1 and Subclass2.
  • Let's say I have another myClass class, with a myField field. I would like to specify that myField's type should be a List of a fixed subclass of Superclass, i.e. either List<Subclass1> or List<Subclass2>.

How should I type myField? List<Superclass> doesn't work since such a list could theoretically contain a combination of Subclass1 and Subclass2 objects... What I'm really looking for here is something like List<subclass(Superclass)>. Does that even exist? How would you go about this?

Again, thanks a lot for the help!

Guillaume


Solution

  • You need to use generics.

    class MyClass<S extends SuperClass> {
      private List<S> myField;
      ...
    }
    

    Hope this helps.