码迷,mamicode.com
首页 > 其他好文 > 详细

泛型的使用

时间:2018-02-17 12:53:48      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:两种   this   ack   color   type   eric   inter   赋值初始化   system   

【泛型类】

 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<T> {
4     //方法引入这个参数时,必须保证该类型参数已在类上声明!
5     public 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 }

 

泛型的使用

标签:两种   this   ack   color   type   eric   inter   赋值初始化   system   

原文地址:https://www.cnblogs.com/schiller-hu/p/8451804.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!