Search code examples
javagenericsinheritancehierarchyparameterized

Overriding type parameters


I'd like to implement the following classes with the following hierarchy:

public class DwellingPropertySetter
    extends AbstractPropertySetter<Dwelling>

public class HousePropertySetter
    extends DwellingPropertySetter<House>

public class SkyscrapperPropertySetter
    extends HousePropertySetter<Skyscrapper>

Unfortunately this code won't compile. A way to do it would be this:

public class DwellingPropertySetter<T extends Dwelling>
    extends AbstractPropertySetter<T>

public class HousePropertySetter<T extends House>
    extends DwellingPropertySetter<T>

public class SkyscrapperPropertySetter<T extends Skyscrapper>
    extends HousePropertySetter<T>

But for me those extends keywords are unnecessary. Whenever I want to use a SkyscrapperPropertySetter I'd have to specify a type parameter. This is useless and would then look like SkyscrapperPropertySetter<Skyscraper>.

Do you know a way out for me? The only other way I know to realise my first hierarchy would be using interfaces and delegate methods.


Solution

  • I think you have correctly recognized it is pointless to have something like ChickenArrayList<Chicken>, so you can either create something like

    class ChickenArrayList extends ArrayList<Chicken>
    

    OR, if you want to reuse some functionality in ChickenArrayList, you may have to make it abstract (and generic) and put another concrete, non-generic class on top of it:

    class AbsChickenArrayList<T extends Chicken> extends ArrayList<T>
    // and
    class ChickenArrayList extends AbsChickenArrayList<Chicken>
    class HenArrayList extends AbsChickenArrayList<Hen>
    

    I know this is quite verbose, but this is the best you can do with this ~18 year old language.