Why is there no type conversion exception in this code?

This is from thinking in Java

class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}

public class AsListInference {
    public static void main(String[] args) {
        //The book says it won't compile, but actually it does.
        List<Snow> snow2 = Arrays.asList(new Light(), new Heavy());
    }
}

Here is my Java environment:

  • java version "1.8.0_60"
  • Java (TM) SE Runtime Environment (build 1.8.0_60-b27)
  • Java HotSpot (TM) 64-bit server VM (build 25.60-b23, mixed mode)
+4
source share
2 answers

Actually, the book is correct. The difference here is in the Java version.

Thinking in Java targets Java 5/6 (according to the cover). For this version of Java (and with Java 7 also) the fragment will not compile with javac. Mistake:

incompatible types: java.util.List<Powder>cannot be converted tojava.util.List<Snow>

With Java 8, this compiles just fine: the I / O system has been improved.

+6
source

, -, , List<Powder>, List<Snow>. , Arrays.<T>asList(T ...) T, , Snow Light, Heavy Snow.

Java 7, Java 8 , , .

+2

Source: https://habr.com/ru/post/1612039/


All Articles