Search code examples
javaoopgenericsextendsgeneric-type-argument

Java Generics: Foo<T>, Foo, Foobar<T extends Foo<T>> and Foobar<T extends Foo>


In Java Generics, given a generic class/interface Foo<T>, What's the difference between declaring a new generic class: Foobar<T extends Foo<T>> or simply Foobar<T extends Foo>, also why can I instantiate a generic class Foo<T> without instantiating the type parameter T?, i.e. why can i write the following: Foo var = new Foo();, does this mean that the class is instantiated with an object, through which i can only use the non-generic method? please forgive me if the question is not so clear, the example i was working on is the following: MyClass<T extends Comparable<T>>


Solution

  • class Foo<T> {}
    

    is your class.

    Foo yourVariable = new Foo();
    

    equals Foo<Object> yourFoo = new Foo<Object>();

    class Foobar<T> extends Foo {}
    

    equals class Foobar<T> extends Foo<Object> {}

    the answer to your question

    class YourClass<T extends Comparable<T>> {}
    

    means YourClass's type T is able to compare itself to objects of T (its class), whereas

    class YourClass<T extends Comparable> {}
    

    's type T is able to compare itself to objects of class Object, which is not what you want