IT序号网

泛型的使用

qq123 2021年05月25日 编程语言 318 0

【泛型类】

 1 package com.hxl; 
 2  
 3 public class GenericityDemo<T> { 
 4     //泛型成员变量无法直接实现非null初始化,需要使用有参构造或set方法赋值初始化 
 5     private T type;         
 6  
 7     public GenericityDemo() { 
 8         super(); 
 9     } 
10  
11     public GenericityDemo(T type) { 
12         super(); 
13         this.type = type; 
14     } 
15  
16     public T getType() { 
17         return type; 
18     } 
19  
20     public void setType(T type) { 
21         this.type = type; 
22     } 
23  
24 }
 1 package com.hxl; 
 2  
 3 public class Test { 
 4  
 5     public static void main(String[] args) { 
 6         // 实例化泛型类并赋非null初始值 
 7         GenericityDemo<Integer> gd = new GenericityDemo<Integer>(new Integer(250)); 
 8         Integer ii = gd.getType(); 
 9         System.out.println(ii); 
10     } 
11 }

【泛型方法】

1 package com.hxl; 
2  
3 public class GenericityDemo { 
4     //方法引入泛型时,必须保证在方法权限修饰符与返回值之间声明这个泛型。 
5     public <T> T show(T t){ 
6         return t; 
7     } 
8 }

【泛型接口及其两种实现方式】

1 package com.hxl; 
2  
3 public interface Generic<T> { 
4     // public abstract 这是接口中抽象方法的默认修饰符,不写也没事 
5     public abstract T show(T t); 
6 }
1 package com.hxl; 
2  
3 public class GenericImpl<T> implements Generic<T> { 
4     // 第一种:该实现类在不明确类型参数T的情况下实现泛型接口 
5  
6     public T show(T t) { 
7         return t; 
8     } 
9 }
1 package com.hxl; 
2  
3 public class GenericImpl implements Generic<String> { 
4     // 第二种:该实现类在明确类型参数T的情况下实现泛型接口 
5  
6     public String show(String s) { 
7         return s; 
8     } 
9 }

评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!