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
Stringto this array (which seems okay since itβs an array ofObject).- However, at runtime, Java discovers youβre trying to put a
Stringinto 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.
