泛型方法

package 泛型;
//泛型方法:

/*泛型类定义的泛型,在整个类中有效,如果被方法使用
那么泛型类的对象明确要操作的具体类型后,所有要操作的类型就
已经固定了。*/
/*为了让不同方法可以操作不同类型,而且类型还不确定。那么可以将泛型定义在方法上*/
/*特殊之处:静态方法不可以访问类上定义的泛型。
 * 如果静态方法操作的应用数据类型不确定,可以将泛型定义在方法上。
 * */
class Demo<T>{//将类型定义在类上
    public void show(T t){
        System.out.println("show"+t);
    }
    public void print(T t){
        System.out.println("print"+t);
    }
    /*public static void method(T t){//错误的方式
        System.out.println("method:"+t);
    }*/
    public static <W> void method(W t){//<W>泛型放在修饰符后面,返回值前面
        System.out.println("method"+t);
    }
}

class Demo1{//将类型定义在方法上
    public <T> void show(T t){
        System.out.println("show:"+t);
    }
    public <Q> void print(Q q){
        System.out.println("print:"+q);
    }
}
//既给类定义了泛型,又在类中定义了泛型方法
class Demo2<T>{
    public void show(T t){
        System.out.println("show:"+t);
    }
    public <Q> void print(Q q){
        System.out.println("print:"+q);
    }
    
}

public class GenericDemo {
    public static void main(String[] args) {
        //将泛型定义在方法上
        Demo1 d = new Demo1();
        d.show("haha");
        d.show(4);
        d.show(new Integer(4));
        d.print(4);
        d.print("hehe");
        
        
        
        //泛型定义在类上的情况
        Demo<String> d1 = new Demo<String>();
        
        d1.show("aaa");
        d1.print("4");
        
        Demo<Integer> d2 = new Demo<Integer>();
        d2.show(new Integer(4));
        d2.print(9);
        
        //既给类定义了泛型,又在类中定义了泛型方法
        Demo2<String> d3 = new Demo2<String>();
        d3.show("haha");
        d3.print(4);
        
    }
    
        
}

posted @ 2016-05-01 22:21  宫学良  阅读(159)  评论(0编辑  收藏  举报