Java 10中var推断的匿名类为何无法互相赋值,其他类型却可以?
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 writenew 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 shareObjectas a common parent. In your jshell example,a1is an instance of one anonymous subclass (let's sayYourCode$1under the hood), whilea2is an instance of a separate, unrelated anonymous subclass (YourCode$2). Jshell uses$1as 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
Thevarkeyword 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 (likeObjecthere). Soa1is typed as that first unique anonymous subclass, anda2as 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 errorincompatible types: $1 cannot be converted to $1is communicating.Long/String work because they're the same concrete type
When you writevar s1 = "test"; var s2 = "another";, both variables are inferred to be of typeString—the exact same concrete class. Similarly,var l1 = 5L; var l2 = 10L;both useLong. 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

