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


  写一个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 }

 

posted @ 2016-09-22 23:01  卡拉瓦  阅读(271)  评论(0编辑  收藏  举报