Why can't we assign two inferred variables as

2019-05-21 16:01发布

问题:

This question already has an answer here:

  • Can a local variable with an inferred type be reassigned to a different type? 2 answers

Java 10 allows to do an anonymous class with a var like:

var a1 = new Object(){};
var a2 = new Object(){};

But this assignment will throw an error:

a1 = a2;

jshell> a1 = a2; | Error: | incompatible types: $1 cannot be converted to $1 | a1 = a2; | ^^

Based on the error log, why can't Java 10 assign two inferred vars as an anonymous class to each other, but it can do the same for other types like Long, String, etc.?

回答1:

Each new Object(){} creates a new type (an anonymous class). These types have no subtype-supertype relation, so it is not possible to assign a1 to a2 and vice versa.

But when you have two long variables, both actually have the same type long, so they are mutually assignable.



标签: java java-10