泛型定义在类和方法上

来源:互联网 发布:驱动管理软件 知乎 编辑:程序博客网 时间:2024/06/06 05:22

//泛型定义在类上

public class Tool<T> {
public void show(T t){
System.out.println("show  " +t);
}
public void print(T t){
System.out.println("print  " +t);
}

}


public class Generi {

public static void main(String[] args) {
Tool<Integer> tr=new Tool<Integer>();
tr.show(new Integer(5));
tr.print(9);
}

}

//**************************************

//泛型定义在方法上

public class Tool {
public <T> void show(T t){
System.out.println("show  " +t);
}
public  <Q>  void print(Q q){
System.out.println("print  " +q);
}

}



public class Generi {
public static void main(String[] args) {
Tool tr=new Tool();
tr.show(new Integer(5));
tr.show("java");
}
}

//**********************

//泛型同时定义在类和方法上

public class Tool <T> {
public  void show(T t){
System.out.println("show  " +t);
}
public  <Q>  void print(Q q){
System.out.println("print  " +q);
}

}


public class Generi {
public static void main(String[] args) {
Tool<String> tr=new Tool<String>();
tr.show("java");
tr.print(3);
tr.print("oracle");
}
}


/*************************************************



public class Tool <T> {
public  void show(T t){
System.out.println("show  " +t);
}
public  <Q>  void print(Q q){
System.out.println("print  " +q);
}
/*编译出错,静态方法不能使用泛型类型(因为泛型类型是随着对象确定而确定的)
 * public static void method(T t){
System.out.println("show  " +t);
}
*/
/*如果静态方法操作的应用数据类型不确定,可以将泛型定义在
 * 方法上
 * 
 * 泛型定义在返回值类型之前,修饰符之后
 */
public static <W >void method(W t){
System.out.println("show  " +t);
}


}

0 0
原创粉丝点击