Search code examples
javaclassgeneric-type-argument

Inherit generic type and force the <type>


Is it possible to inherit generic type and to force in the child class the type received?

Something like:

class A<GenericType>{}
class B extends A<GenericType>{}

Or:

class B <PreciseType> extends A <GenericType>{}

But where do I define the GenericType used in B?


Solution

  • Given

    class A<T> {}
    

    It depends on what you try to do, but both options are possible:

    class B extends A<SomeType> {};
    B bar = new B();
    A<SomeType> foo = bar; //this is ok
    

    and

    class B<T> extends A<T>{}; //you could use a name different than T here if you want
    B<SomeType> bar = new B<SomeType>();
    A<SomeType> foo = bar; //this is ok too
    

    But keep in mind that in the first case SomeType is an actual class (like String) and in the second case T is a generic type argument that needs to be instantiated when you declare/create objects of type B.

    As a piece of advice: using generics in collections is easy and straightforward, but if you want to create your own generic classes you really need to understand them properly. There are a few important gotchas about their variance properties, so read the tutorial carefully and many times to master them.