黑马程序员技术交流社区
标题:
6 泛型定义在接口上
[打印本页]
作者:
itheima_llt
时间:
2015-4-16 13:20
标题:
6 泛型定义在接口上
/*
方式一:类继承接口后指定了类型Integer
interface Inter<T>
{
void show(T t);
}
class InterImpl implements Inter<Integer>
{
public void show(Integer i)
{
System.out.println(i);
}
}
class GenericDemo5
{
public static void main(String[] args)
{
InterImpl i = new InterImpl();
i.show(new Integer(88));
}
}
*/
//方式二:类继承接口后,还是不确定引用数据类型,继续使用泛型
interface Inter<T>
{
<Q>void show(Q q);//泛型定义在方法上,仅仅在方法内有效
void print(T t);//跟泛型类走
}
class InterImpl<T> implements Inter<T>
{
public <Q> void show(Q t)//泛型跟方法走
{
System.out.println(t);
}
public void print(T t)//泛型跟类走
{
System.out.println("类T:"+t);
}
}
class GenericDemo5
{
public static void main(String[] args)
{
InterImpl<String> i = new InterImpl<String>();
i.show(new Integer(88));
i.show(new String("s88"));
i.print(new String("s88"));
//i.print(new Integer(88));//编译不能通过
}
}
复制代码
[attach]68980[/attach]
使用泛型编译无法通过.jpg
(146.3 KB, 下载次数: 34)
下载附件
2015-4-16 13:19 上传
作者:
itheima_llt
时间:
2015-4-16 13:21
所以,泛型定义在方法上是非常有好处的!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2