泛型类:其本质是参数化类型,把类型作为参数传递
package Dey01;
/*
* <泛型类>
* 语法:类名<T>
* T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
*/
public class MyGenericity<T> {
//1.用它创建变量
T t;
//2.泛型作为方法的参数
public void show(T t){
System.out.println(t);
}
//3.泛型作为方法的返回值
public T getT(){
return t;
}
}
测试类:
package Dey01;
public class TsetGenericity {
public static void main(String[] args) {
//使用泛型类来创建对象(T的类型只能是引用类型!)
//---------------string类型-----------------
MyGenericity<String> myGenericity = new MyGenericity<String>();
//调用·t
myGenericity.t="我爱你!1";
myGenericity.show("我爱你!2");
String string=myGenericity.getT();
System.out.println(string);
//---------------int类型-----------------
MyGenericity<Integer> myGenericity2 = new MyGenericity<Integer>();
myGenericity2.t=123;
myGenericity2.show(456);
Integer integer = myGenericity2.getT();
System.out.println(integer);
测试结果:
我爱你!2
我爱你!1
456
123