Abstract
- Let be a complex type based on type . The complex type can be Covariant, Contravariant and Invariant
Covariant
- Given two datatypes and and as the complex type,
Covariance in Java arrays can lead to runtime errors
Java Arrays are Covariant.
- Imagine you have an array of
Integer
.- Due to covariance, you can assign this array to a variable declared as an array of
Object
.- Now, you might try to add a
String
to this array (which seems okay since it’s an array ofObject
).- However, at runtime, Java discovers you’re trying to put a
String
into an array meant forInteger
, causing an error.
Contravariant
- Given two datatypes and and as the complex type,
Invariant
- If complex type is neither Covariant nor Contravariant
Invariants in Java
Primitive arrays and Generics are invariant.