笔记:
/**1.定义一个PairTest泛型类, 测试泛型 类 Pair的用法 * class Pair<T>{ * private T first; * private T second; * ............(方法get/set 全部自动生成) * } * 2.泛型方法的使用; 创建一个泛型方法: 格式: [public...访问修订符] [static][final] <T> void classname(T x){ ... } * 3.类型通配符为'?',仅可以用来声明变量!不可以声明类! void showClassName(Status<?>ob) ;默认上界是 Number */
测试代码:
public class Test泛型 { public static void main(String[] args){ //1.定义一个PairTest类, 测试泛型类Pair的用法 Pair<String> pair=new Pair<String>("Hello","Java"); System.out.print("first = "+pair.getFirst()); System.out.println(", second = "+pair.getSecond()); System.out.println("-----------------------------"); //2.泛型方法的使用; 创建一个泛型方法; GenericMethod gm = new GenericMethod(); gm.showClassName("c"); gm.showClassName(1); gm.showClassName('a'); gm.showClassName(gm); //3.通配类型参数; Integer inums[]={1,2,3,4,5}; Status<Integer> iobj=new Status<>(inums); Double dnums[]={1.1,2.2,3.3,4.4,5.5}; Status<Double> dobj=new Status<>(dnums); iobj.showClassName(iobj); iobj.showClassName(dobj); //将void showClassName(Status<T>ob) 改为:void showClassName(Status<?>ob) } } class Pair<T>{ private T first; private T second; public Pair() { this.first = null; this.second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public void setFirst(T first) { this.first = first; } public T getSecond() { return second; } public void setSecond(T second) { this.second = second; } } class GenericMethod{ public <T> void showClassName(T x){ System.out.println(x+"'s classname: "+x.getClass().getName()); } } class Status<T extends Number>{ T[] nums; public Status(T[] nums) { this.nums = nums; } void showClassName(Status<?>ob){ System.out.println("[3] classname: "+ob.getClass().getName()); } }
测试结果:
first = Hello, second = Java ----------------------------- c's classname: java.lang.String 1's classname: java.lang.Integer a's classname: java.lang.Character 任务168.GenericMethod@3567135c's classname: 任务168.GenericMethod [3] classname: 任务168.Status [3] classname: 任务168.Status