- /*
- 方式一:类继承接口后指定了类型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));//编译不能通过
- }
- }
复制代码
|
|