Skip to content

Instantly share code, notes, and snippets.

@thomas-holmes
Last active June 29, 2016 14:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomas-holmes/835398747f766f6b0fc35182827f487b to your computer and use it in GitHub Desktop.
Save thomas-holmes/835398747f766f6b0fc35182827f487b to your computer and use it in GitHub Desktop.
covariance fail
// Assume Cat and Dog are descendants of Animal. Yes I know this is a garbage example of inheritance
public class Foo {
public void failAppend(List<Cat> catList) {
Cat cat = new Cat();
Dog dog = new Dog();
Aniaml animal = new Cat();
catList.append(cat); // Obviously can do this
catList.append(dog); // Obviously can't do this
catList.append(animal); // (Slightly less) obviously can't do this.
failAppend(catList, dog); // Whoops runtime error. We just put a dog into a list statically typed as containing only Cats
}
public void failAppend(List<Animal> animals, Animal a) {
animals.append(a); // Duh, obviously we can do this!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment