JavaSE-15.3.2【泛型类】

 1 package day6.lesson3.p2;
 2 
 3 /*
 4 3.2 泛型类
 5 
 6     格式:
 7         修饰符 class 类名<类型> { }
 8 
 9  */
10 public class GenericDemo {
11     public static void main(String[] args) {
12         Student s = new Student();
13         s.setName("tom");
14         System.out.println(s.getName());
15 
16         Teacher t = new Teacher();
17         t.setAge(30); //自动装箱
18 //        t.setAge("30"); //编译异常
19         System.out.println(t.getAge());
20 
21         System.out.println();
22 
23         Generic<String> g1 = new Generic<>();
24         g1.setT("tom");
25         System.out.println(g1.getT());
26 
27         Generic<Integer> g2 = new Generic<>();
28         g2.setT(30);
29         System.out.println(g2.getT());
30     }
31 }
 1 package day6.lesson3.p2;
 2 
 3 public class Generic<T> {
 4 
 5     private T t;
 6 
 7     public void setT(T t) {
 8         this.t = t;
 9     }
10 
11     public T getT() {
12         return t;
13     }
14 }
 1 package day6.lesson3.p2;
 2 
 3 public class Student {
 4 
 5     private String name;
 6 
 7     public void setName(String name) {
 8         this.name = name;
 9     }
10 
11     public String getName() {
12         return name;
13     }
14 }
 1 package day6.lesson3.p2;
 2 
 3 public class Teacher {
 4 
 5     private Integer age;
 6 
 7     public void setAge(Integer age) {
 8         this.age = age;
 9     }
10 
11     public Integer getAge() {
12         return age;
13     }
14 }

 

posted @ 2021-06-01 17:05  yub4by  阅读(44)  评论(0编辑  收藏  举报