问题
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 var
s 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.
来源:https://stackoverflow.com/questions/49580431/why-cant-we-assign-two-inferred-variables-as-an-anonymous-class-to-each-other