为什么在实例化通用外部类(连同内部类)时使用菱形运算符会在代码段 2 中产生错误,而代码段 1 却完全没问题?
我知道稀有类型是被禁止的,但我的情况不是稀有类型——在稀有类型中,外部和内部都是通用的,但其中一个(任一)用作原始类型,另一个用作通用类型。
片段 1:
class Outer {
class Inner {
}
}
class Driver {
public static void main(String[] args) {
Outer.Inner obj1 = new Outer().new Inner<>(); // fine !
Outer.Inner obj2 = new Outer().new Inner<>(); // fine !
}
}
片段 2:
class Outer {
class Inner {
}
}
class Driver {
public static void main(String[] args) {
Outer.Inner obj1 = new Outer<>().new Inner(); // fine !
Outer.Inner obj2 = new Outer<>().new Inner(); // error !
}
}
附言在 Eclipse 编译器上测试。
您正在尝试使用菱形运算符来推断类型参数:
Outer.Inner obj2 = new Outer<>().new Inner(); // error !
JLS, section 15.9 ,关于钻石的说法:
A class instance creation expression specifies a class to be instantiated, possibly followed by type arguments (§4.5.1) or a diamond (<>) if the class being instantiated is generic
你有两个类实例化表达式:
new Outer<>()
Và
new Inner() // or more precisely, new Outer<>().new Inner()
在 15.9 节的末尾,它区分了这两个表达式:
A class instance creation expression is a poly expression (§15.2) if it uses the diamond form for type arguments to the class, and it appears in an assignment context or an invocation context (§5.2, §5.3). Otherwise, it is a standalone expression.
因此,第二个表达式是一个多边形表达式,这意味着它的类型取决于赋值上下文;但是第一个表达式,new Outer<>()
, 是一个独立的表达式:它的类型不受任何上下文的影响。
你的其他声明
Outer.Inner obj2 = new Outer<>().new Inner();
很好,因为您使用的是 Outer
作为原始类型。
Tôi là một lập trình viên xuất sắc, rất giỏi!