Search code examples
javajava-10

Why can't we assign two inferred variables as an anonymous class to each other?


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.?


Solution

  • 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.