You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java 10中var推断的匿名类为何无法互相赋值,其他类型却可以?

Why can't var-inferred anonymous class variables be assigned to each other in Java 10?

Great question! Let's break this down clearly to understand what's going on here:

  • Every anonymous class is a unique, distinct type
    Even if you write new Object(){} twice with identical code inside the braces, the compiler generates a completely new subclass of Object each time. These classes have no inheritance relationship with each other—they only share Object as a common parent. In your jshell example, a1 is an instance of one anonymous subclass (let's say YourCode$1 under the hood), while a2 is an instance of a separate, unrelated anonymous subclass (YourCode$2). Jshell uses $1 as a placeholder for both in the error message, which is a bit confusing, but they're definitely different types.

  • var infers the exact concrete type, not the parent class
    The var keyword infers a variable's type based on the actual runtime type of the expression on the right-hand side. It doesn't fall back to the parent class (like Object here). So a1 is typed as that first unique anonymous subclass, and a2 as the second. Since these two classes don't extend each other, you can't assign an instance of one to a variable of the other type—that's exactly what the error incompatible types: $1 cannot be converted to $1 is communicating.

  • Long/String work because they're the same concrete type
    When you write var s1 = "test"; var s2 = "another";, both variables are inferred to be of type String—the exact same concrete class. Similarly, var l1 = 5L; var l2 = 10L; both use Long. Since they're instances of the identical type, assigning them to each other is allowed without issue.

To test this logic, try explicitly typing the variables as Object instead of using var:

Object a1 = new Object(){};
Object a2 = new Object(){};
a1 = a2; // This works perfectly!

Here, we're treating both instances as their parent type (Object), so the assignment is valid. But with var, we're locked into the unique anonymous subclass types, which aren't compatible.

内容的提问来源于stack exchange,提问作者hoan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:18:43