What are alternatives to variance and invariance and how do they compare?

In programming, especially in object-oriented languages, variance and invariance determine how subtypes relate to their parent types. Alternatives include contravariance and covariance.

variance, invariance, contravariance, covariance, object-oriented programming, type safety

<?php // Example of Covariance class Animal { public function makeSound() { return "Some sound"; } } class Dog extends Animal { public function makeSound() { return "Bark"; } } function getAnimal(): Animal { return new Dog(); // Covariant return type } $animal = getAnimal(); echo $animal->makeSound(); // Outputs: Bark ?>

variance invariance contravariance covariance object-oriented programming type safety