泛型类

//泛型类:类名<T> ,T是类型占位符,表示一种引用类型,如果编写多个,使用逗号隔开
public class MyGeneric<T> {
//1.创建变量
T t;

//2.添加方法:泛型作为方法的参数
public void show(T t){
System.out.println(t);
}

//3.泛型作为方法的返回值
public T getT(){
return t;
}
}


public  class Demo01 {
public static void main(String[] args) {
//使用泛型类创建对象
//注意:1.泛型只能使用引用类型 2.不同泛型对象不能相互复制

MyGeneric<String> myGeneric1 = new MyGeneric<>();
myGeneric1.t="hello";
myGeneric1.show("java");//java
String s = myGeneric1.getT();
System.out.println(s);//hello

MyGeneric<Integer> myGeneric2 = new MyGeneric<>();
myGeneric2.t=10;
myGeneric2.show(20);//20
Integer t = myGeneric2.getT();
System.out.println(t);//10

//MyGeneric<int> myGeneric3 = new MyGeneric<>(); 泛型只能使用引用类型
//MyGeneric<String> myGeneric4=myGeneric2; 不同泛型对象不能相互复制
}
}

posted @ 2023-02-20 10:00  惊鸿宴远赴人间  阅读(23)  评论(0)    收藏  举报