泛型(8)-Java7的"菱形"语法与泛型构造器

   正如泛型方法允许在方法签名中声明泛型形参一样,Java也允许在构造器签名中声明泛型形参,这样就产生了所谓的泛型构造器.

package com.j1803;
class Foo{
public <T> Foo(T t){
System.out.println(t);
}
}
public class GenericConstructor {
public static void main(String[] args) {
//泛型构造器中的T类型为String
new Foo("AAAA");
//泛型构造器中T类型为Integer
new Foo(45);

//显示指定泛型构造器中的T类型为String
//传给Foo构造器的实参也是String对象,完全正确
new <String>Foo("BBBB");

//显示指定泛型构造器中的T类型为String
//传给Foo构造器的实参确实Double对象,编译错误
//new <String>Foo(45.23);//编译错误
}
}
 new <String>Foo("BBBB");不仅显示指定了泛型构造器中泛型形参T的类型应该是String,而且程序传给该构造器的参数值也是String类型,因此程序完全正确,而在new <String>Foo(45.23);总则因为类型不同而出现编译错误.
Java7新增的"菱形"语法,它允许调用构造器时在构造器后使用一对尖括号来代表泛型信息,但如果程序显示地指定了泛型构造器中声明的泛型形参的实际类型,则不可以使用"菱形"语法.
package com.j1803.Type_wildcards;
class MyClass<E>{

public <T>MyClass(T t){
System.out.println("t的参数是:"+t);
}
}
public class GenericDiamondTest {
public static void main(String[] args) {
//MyClass类声明中的EString类型
//泛型构造器中声明的T形参是Integer类型
MyClass<String> mc1=new MyClass<>(5);

//显示指定泛型构造器中声明的T形参是Integer类型
MyClass<String> mc2=new <Integer>MyClass<String>(6);

//MyClass类声明中的EString类型
//如果显示指定泛型构造器中声明的T形参是Integer;
//此时就不能使用"菱形"语法,下列代码是错的.
//MyClass<String>mc3=new <Integer> MyClass<>(5);
}
}
上面的代码中即制定了泛型构造器的泛型参数是Integer类型,又想使用"菱形"语法,所以这行代码无法通过编译
 

猜你喜欢

转载自www.cnblogs.com/shadow-shine/p/9665787.html