Last active
June 29, 2016 14:57
-
-
Save thomas-holmes/835398747f766f6b0fc35182827f487b to your computer and use it in GitHub Desktop.
covariance fail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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