Last active
January 2, 2017 08:48
-
-
Save thieux/8512b0447fc2f23e3d5138e73908f1ae to your computer and use it in GitHub Desktop.
How Java array covariance is bad
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
import org.junit.Test; | |
public class ArrayCovarianceTest { | |
@Test(expected = ArrayStoreException.class) | |
public void cat_should_not_be_set_in_dog_list() { | |
Animal[] animals = new Dog[1]; // array covariance | |
// Java compiler allows the assignment because Dog extends Animal | |
// But the Java runtime throws a "java.lang.ArrayStoreException: Cat" | |
animals[0] = new Cat(); | |
} | |
class Animal { | |
} | |
class Dog extends Animal { | |
} | |
class Cat extends Animal { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment