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 enviroment:
Swapping the inappropriate constructor call with an instance of the correct type solves the issue, as shown in Fig. 6(b). Fig. 6 also serves as an example to show how the incompatible types error is, in fact, a generalization of the method X in class Y cannot be applied to given types error explored in [4].
The IllegalFormatConversionException is an unchecked exception in Java that occurs when the argument that corresponds to a format specifier is of an incompatible type. Since the IllegalFormatConversionException is thrown at runtime, it does not need to be declared in the throws clause of a method or constructor.
In type casting, a data type is converted into another data type by a programmer using casting operator. Whereas in type conversion, a data type is converted into another data type by a compiler.
Class IllegalFormatExceptionUnchecked exception thrown when a format string contains an illegal syntax or a format specifier that is incompatible with the given arguments. Only explicit subtypes of this exception which correspond to specific errors should be instantiated.
Actually, the book is right. The difference here is the Java version.
Thinking in Java targets Java 5/6 (as per the cover). For this version of Java (and with Java 7 also), the snippet won't compile with javac
. The error is:
incompatible types:
java.util.List<Powder>
cannot be converted tojava.util.List<Snow>
With Java 8, this compiles just fine: the type-inference system was improved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With