问题描述
请给出一个有关Java中协方差和逆方差的好例子.
Please show a good example for covariance and contravariance in Java.
推荐答案
协方差:
class Super {
Object getSomething(){}
}
class Sub extends Super {
String getSomething() {}
}
Sub#getSomething是协变的,因为它返回Super#getSomething的返回类型的子类(但完全履行了Super.getSomething()的约定)
Sub#getSomething is covariant because it returns a subclass of the return type of Super#getSomething (but fullfills the contract of Super.getSomething())
矛盾性
class Super{
void doSomething(String parameter)
}
class Sub extends Super{
void doSomething(Object parameter)
}
Sub#doSomething是互变的,因为它采用了Super#doSomething的参数的超类的参数(但同样,它满足了Super#doSomething的约定)
Sub#doSomething is contravariant because it takes a parameter of a superclass of the parameter of Super#doSomething (but, again, fullfills the contract of Super#doSomething)
注意:此示例在Java中不起作用. Java编译器将重载并且不会覆盖doSomething()-Method.其他语言也支持这种类型的逆变.
泛型
这对于泛型也是可能的:
This is also possible for Generics:
List<String> aList...
List<? extends Object> covariantList = aList;
List<? super String> contravariantList = aList;
现在,您可以访问所有不带通用参数的covariantList
方法(因为必须是扩展对象"),但是getter可以正常工作(作为返回的对象)将始终为对象"类型)
You can now access all methods of covariantList
that doesn't take a generic parameter (as it must be something "extends Object"), but getters will work fine (as the returned object will always be of type "Object")
contravariantList
的情况相反:您可以使用泛型参数访问所有方法(您知道它必须是"String"的超类,因此您始终可以传递一个),但是没有吸气剂(返回的类型可能是字符串的任何其他超类型)
The opposite is true for contravariantList
: You can access all methods with generic parameters (you know it must be a superclass of "String", so you can always pass one), but no getters (The returned type may be of any other supertype of String)
这篇关于给出一些函数示例,这些函数在Java中的重载和重载情况下表现出协方差和矛盾.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!