类上的泛型和接口泛型

package demo.assemble;

//接口泛型
interface Inter<T> {
    public abstract void show(T e);
}

//将泛型定义在类上
class Tool<T> {
    private T data;

    //将泛型定义在静态函数上   此时静态函数无法使用类上定义的泛型
    static <Tp> void print(Tp e) {
        System.out.println(e);
    }

    T getData() {
        return data;
    }

    void setData(T data) {
        this.data = data;
    }

    //将泛型定义在方法上
    <Ts> void show(Ts e) {
        System.out.println(e);
    }
}

class InterImpl implements Inter<String> {
    public void show(String e) {
        System.out.println(e);
    }
}

class InterImpl2<T> implements Inter<T> {
    public void show(T e) {
        System.out.println(e);
    }
}

class 泛型 {
    public static void main(String[] args) {
//        genericityInClass();//类上的泛型
        genericityInInterface();//接口泛型
    }

    //类上的泛型
    private static void genericityInClass() {
        //类上的泛型
        Tool<Student> tool = new Tool<>();
        tool.setData(new Student("a", 18));
        //普通方法上的泛型
        tool.show(new Student("b", 19));
        tool.show(new String("xcvxc"));
        //静态方法上的泛型
        Tool.print(new Person("c", 22));
    }

    //接口泛型
    private static void genericityInInterface() {
        InterImpl inter = new InterImpl();
        inter.show("ada");
//        inter.show(2);//error

        InterImpl2<Integer> inter2 = new InterImpl2<>();
        inter2.show(2);
//        inter2.show("ada");//error
    }
}
/**
 * * 在泛型里面写是一个对象,String 不能写基本的数据类型 比如int (****)
 * ** 写基本的数据类型对应包装类
 * byte -- Byte
 * short -- Short
 * <p>
 * int -- Integer
 * <p>
 * long -- Long
 * <p>
 * float -- Float
 * double -- Double
 * <p>
 * char   -- Character
 * <p>
 * boolean -- Boolean
 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值