Joe
Joe

Reputation: 7919

Generic with a lower bounded wildcard <? super Dog>

class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}
public class Mixer<A extends Animal>{
    public <C extends Cat> Mixer<? super Dog> useMe(A a, C c){
        //return new Mixer<Object>();//KO
        return new Mixer<Animal>(); //OK
    }
}

The return parameter is Mixer<? super Dog> so if is a defined with a lower bounded wildcard

Why do I have a compiler error when I return a Mixer<Object> and there is no compiler error with Mixer<Animal>?

Upvotes: 2

Views: 305

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213311

The problem is not in the return type of your method, rather it is the Generic Type bound to your class Mixer.

Let's see what went wrong: -

public <C extends Cat> Mixer<? super Dog> useMe(A a, C c)

The return type Mixer<? super Dog> means, you can return any Mixer of type Dog or a super-type of Dog, may be Animal.

    //return new Mixer<Object>();//KO
    return new Mixer<Animal>(); //OK

So, both the return statments would have worked fine, because, both Animal and Object is a super-type of Dog.

But, the reason why the first one does not fits in is because, you have declared your class as: -

public class Mixer<A extends Animal>

So, you have bound your type that can be associated with Mixer class to either Animal or its subtype. Now, since, Object is not a subtype of Animal, you can't just create: -

new Mixer<Object>();

So, you can create instances of your class like:-

new Mixer<Animal>(); // OR
new Mixer<Dog>();  // Dog extends Animal  // OR
new Mixer<Cat>();  // Cat extends Animal

// **** But NOT like this ******
new Mixer<Object>();  // Object does not extend Animal

Upvotes: 6

Related Questions