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

。_饼干妹妹 提交于 2020-01-14 02:56:21

问题


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.



来源:https://stackoverflow.com/questions/49580431/why-cant-we-assign-two-inferred-variables-as-an-anonymous-class-to-each-other

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!