首页  :: 新随笔  :: 管理

java 泛型接口示例

Posted on 2016-08-23 12:49  季枫  阅读(429)  评论(0编辑  收藏  举报
/*
 * 泛型接口
 */
interface Tool<t> {
    public void show(T t);
     
    //泛型方法
    public <e> void print(E e);
}
 
/*
 * 这种方式适合实现接口的时候就知道类里的泛型是什么
 */
class ToolImpl implements Tool<string> {
 
    @Override
    public void show(String t) {
        System.out.println("show:" + t);
    }
 
    @Override
    public <e> void print(E e) {
        System.out.println("print:" + e);
    }
 
}
 
/*
 * 这种方式不好!
 */
class Tool2Impl implements Tool {
 
    @Override
    public void show(Object t) {
        System.out.println("show obj" + t);
    }
 
    @Override
    public void print(Object e) {
        System.out.println("show obj" + e);
    }
 
}
 
/*
 * 这种方式适合使用的时候指定泛型 
 * 在继承接口的时候不用指定泛型 
 * 注意的是<t>也可以写成别的比如<c> 
 * 写成<e>的话,类上的<e>和print方法
 * 上的<e>也不是一个类型
 */
class Tool3Impl<t> implements Tool<t> {
 
    @Override
    public void show(T t) {
        System.out.println("show=" + t);
    }
 
    @Override
    public <e> void print(E e) {
        System.out.println("print=" + e);
    }
 
}
 
/*
 * 这个写法中show方法和print方法用的泛型也不是一个 
 * 类上的<e>和print方法上的<e>不是一个类型!!!
 */
class Tool4Impl<e> implements Tool<e> {
 
    @Override
    public void show(E t) {
        System.out.println("show-" + t);
    }
 
    @Override
    public <e> void print(E e) {
        System.out.println("print-" + e);
    }
 
}
 
/*
 * 错误!
 * class Tool5Impl<string> implements Tool<t> {
 * 
 * }
 */
/*
 * 正确,但是这个泛型上的String没意义,和Tool3Impl写法没区别 
 * class Tool5Impl<string, t=""> implements Tool<t> {
 * 
 * }
 */
/*
 * 错误1 
 * class Tool5Impl<string|t> implements Tool<e> {
 * 
 * }
 */
/*
 * 正确,但是这个泛型上的String|T没意义,和Tool4Impl写法没区别 
 * class Tool6Impl<string|t, e=""> implements Tool<e> {
 * 
 * }
 */
public class GenericDemo {
 
    public static void main(String[] args) {
        ToolImpl ti = new ToolImpl();
        ti.show("nihao");
        ti.print(6);
        Tool3Impl<string> t3i = new Tool3Impl<string>();
        t3i.show("haha");
        t3i.print(6);
        Tool4Impl<string> t4i = new Tool4Impl<string>();
        t4i.show("hehe");
        t4i.print(6);
    }
 
}

  

智读 | 成都会领科技有限公司官网 | 智读App下载 | 每天听本书的博客 | |