码迷,mamicode.com
首页 > 编程语言 > 详细

java 16 -7 泛型方法和泛型接口(泛型类相似)

时间:2016-09-22 23:49:41      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:


  写一个ObjectTool类

  泛型方法:把泛型定义在方法上
    格式 public <泛型类型> 返回类型 方法名(泛型类型)
  这样的好处是:
    这个泛型方法可以接收任意类型的数据

1 public class ObjectTool {
2 public <T> void show(T t) {
3 System.out.println(t);
4 }
5 }

 


  再写一个测试类

1 public class ObjectToolDemo {
2 public static void main(String[] args) {
3 ObjectTool ot = new ObjectTool();
4 ot.show("hello");
5 ot.show(100);
6 ot.show(true);
7 }
8 }

 


  先写一个泛型接口类
    泛型接口:把泛型定义在接口上


1 public interface Inter<T> {
2 public abstract void show(T t);
3 }

 

实现类:

 1 /* 
 2 实现类在实现接口的时候    
 3 第一种情况:已经知道该是什么类型的了
 4 */
 5 //public class InterImpl implements Inter<String> {
 6 //
 7 //    @Override
 8 //    public void show(String t) {
 9 //    System.out.println(t);
10 //    }
11 // }
12 
13 //第二种情况:还不知道是什么类型的
14 public class InterImpl<T> implements Inter<T> {
15 
16 @Override
17 public void show(T t) {
18 System.out.println(t);
19 }
20 }
21 
22 /*    

 

测试类

 1 public class InterDemo {
 2 public static void main(String[] args) {
 3 // 第一种情况的测试
 4 // Inter<String> i = new InterImpl();
 5 // i.show("hello");
 6 
 7 // // 第二种情况的测试
 8 Inter<String> i = new InterImpl<String>();
 9 i.show("hello");
10 
11 Inter<Integer> ii = new InterImpl<Integer>();
12 ii.show(100);
13 }
14 }

 

java 16 -7 泛型方法和泛型接口(泛型类相似)

标签:

原文地址:http://www.cnblogs.com/LZL-student/p/5898309.html

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