[英]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>
返回参数是Mixer<? super Dog>
Mixer<? super Dog>
so if is a defined with a lower bounded wildcard Mixer<? super Dog>
因此如果是使用下界通配符定义的
Why do I have a compiler error when I return a Mixer<Object>
and there is no compiler error with Mixer<Animal>
? 为什么当我返回Mixer<Object>
并且Mixer<Animal>
没有编译器错误时出现编译器错误?
The problem is not in the return type of your method, rather it is the Generic Type
bound to your class Mixer
. 问题不在于方法的返回类型,而在于绑定到您的类Mixer
的Generic Type
。
Let's see what went wrong: - 让我们看看出了什么问题:-
public <C extends Cat> Mixer<? super Dog> useMe(A a, C c)
The return type Mixer<? super Dog>
返回类型Mixer<? super Dog>
Mixer<? super Dog>
means, you can return any Mixer
of type Dog
or a super-type
of Dog, may be Animal
. Mixer<? super Dog>
意味着,您可以返回Dog
类型的任何Mixer
或Dog
的super-type
,可以是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
. 因此,两个return
语句都可以正常工作 ,因为Animal
和Object
都是Dog
的super-type
。
But , the reason why the first one
does not fits in is because, you have declared your class as: - 但是 , first one
不适合的原因是,您已将类声明为:-
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
. 因此,您已经将可以与Mixer
类关联的type
bound
到Animal
或其subtype
。 Now, since, Object
is not a subtype of Animal
, you can't just create: - 现在,由于Object
不是Animal
的子类型,因此您不能只创建:-
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.