Covariance and contravariance (computer science): Difference between revisions

Content deleted Content added
Bivariance means equality of types.
Tags: Reverted Visual edit Mobile edit Mobile web edit
manual RV: wrong plus contradicts the rest of the article
Line 109:
 
== Inheritance in object-oriented languages ==
When a subclass [[Method overriding|overrides]] a method in a superclass, the compiler must check that the overriding method has the right type. While some languages require that the type exactly matches the type in the superclass (bivarianceinvariance), it is also type safe to allow the overriding method to have a "better" type. By the usual subtyping rule for function types, this means that the overriding method should return a more specific type (return type covariance) and accept a more general argument (parameter type contravariance). In [[Unified Modeling Language|UML]] notation, the possibilities are as follows (where Class B is the subclass that extends Class A which is the superclass):
 
<gallery perrow="5" heights="190" caption="Variance and method overriding: overview">
Image:Vererbung T.svg|Subtyping of the parameter/return type of the method.
Image:Inheritance_invariant.svg|''BivarianceInvariance''. The signature of the overriding method is unchanged.
Image:Inheritance_covariant_return.svg|''Covariant return type''. The subtyping relation is in the same direction as the relation between ClassA and ClassB.
Image:Inheritance_contravariant_argument.svg|''Contravariant parameter type''. The subtyping relation is in the opposite direction to the relation between ClassA and ClassB.