自定义类使用泛型and方法使用泛型

使用泛型的自定义类,泛型可以使用任意的数据类型,在创建对象的时候确定是什么数据类型,创建对象的时候不使用泛型,那就默认是Object类型
格式:

使用泛型的自定义类

package cn.zhuobo.day10.aboutGeneric;

public class ClassGeneric<E> {
    private E name;

    public ClassGeneric() {
    }

    public ClassGeneric(E name) {
        this.name = name;
    }

    public E getName() {
        return name;
    }

    public void setName(E name) {
        this.name = name;
    }
}

创建对象

package cn.zhuobo.day10.aboutGeneric;

public class MainGeneric {
    public static void main(String[] args) {
        ClassGeneric<String> a = new ClassGeneric<>();
        ClassGeneric<Integer> b = new ClassGeneric<>();
    }
}

含有泛型的方法:

格式:泛型定义在方法的返回值类型和权限修饰符之间

修饰符 <泛型> 返回值类型 方法名(使用泛型的参数列表) {

} 

含有泛型的方法,在调用的时候确定数据类型,传递的参数是什么类型,泛型就是什么类型

public <M> void method(M m) {
        System.out.println(m);
}

public static  <M> void method11(M m, int a) {
        if(a > 0) System.out.println(m);
}

猜你喜欢

转载自www.cnblogs.com/zhuobo/p/10625332.html