泛型方法有三种:一、与类的泛型捆绑;二、独立于类的类型;三、静态方法的泛型
定义如图所示:
下面是实现上面三种方法的代码实现:
package cn.hncu.generic.two;
public class Demo3 {
public static void main(String[] args) {
//t1();
//t2();
t3();
}
//1类上的泛型演示(方法上的泛型和类上的捆绑)
private static void t1() {
Tool<String> t1 = new Tool<String>();
t1.show("abc123");
//t1.show(new Integer(100));//ERROR
Tool<Integer> t2 = new Tool<Integer>();
t2.show(new Integer(100));
//t2.show("abc123");//ERROR
}
//2方法上的泛型演示(独立于类上的泛型)
public static void t2(){
Tool<String> t1 = new Tool<String>();
t1.print("abc123");
//Integer i = t1.print2("abc123");//ERROR
String str = t1.print2("aaa123");
System.out.println(str);
//int型 转化成 String型
String str2 =String.valueOf(100);
System.out.println(str2);
String str3 =""+100;
System.out.println(str3);
//String str4 =(String) (100);//不行
}
//3方法上的泛型演示(静态方法上的)
public static void t3(){
Tool.aa(123);
Tool.aa("abcd112");
}
}
class Tool<W>{
public void show(W w){
System.out.println("show:" + w.toString());
}
public <A> void print( A a){//方法上面的泛型
System.out.println(a);
//return a;
}
public <B> B print2( B a){//方法上面的泛型
System.out.println(a);
return a;
}
/*静态方法上的泛型不能使用类上的,下面是出错的
public static void aa(W w){
System.out.println("static aa:");
}
*/
//静态方法上的泛型,要自己定义(不能引用类上的)
public static<Y> void aa(Y y){
System.out.println("static aa:"+y);
}
}