Java——集合——泛型——定义和使用含有泛型的接口

定义和使用含有泛型的接口

定义格式:

修饰符 interface接口名<代表泛型的变量> {  }


1.定义一个含有泛型的类

package com.itheima.demo03.Generic;
/* 定义含有泛型的接口 */ public interface GenericInterface<I> { public abstract void method(I i); } 

2.实现类1

package com.itheima.demo03.Generic;
/* 含有泛型的接口,第一种使用方式:定义接口的实现类,实现接口,指定接口的泛型 public interface Iterator<E> { E next(); } Scanner类实现了Iterator接口,并指定接口的泛型为String,所以重写的next方法泛型默认就是String public final class Scanner implements Iterator<String>{ public String next() {} } */ public class GenericInterfaceImpl1 implements GenericInterface<String>{ @Override public void method(String s) { System.out.println(s); } } 

实现类2

package com.itheima.demo03.Generic;

/* 含有泛型的接口第二种使用方式:接口使用什么泛型,实现类就使用什么泛型,类跟着接口走 就相当于定义了一个含有泛型的类,创建对象的时候确定泛型的类型 public interface List<E>{ boolean add(E e); E get(int index); } public class ArrayList<E> implements List<E>{ public boolean add(E e) {} public E get(int index) {} } */ public class GenericInterfaceImpl2<I> implements GenericInterface<I> { @Override public void method(I i) { System.out.println(i); } } 

测试类

package com.itheima.demo03.Generic;
/* 测试含有泛型的接口 */ public class Demo04GenericInterface { public static void main(String[] args) { //创建GenericInterfaceImpl1对象 GenericInterfaceImpl1 gi1 = new GenericInterfaceImpl1(); gi1.method("字符串"); //创建GenericInterfaceImpl2对象 GenericInterfaceImpl2<Integer> gi2 = new GenericInterfaceImpl2<>(); gi2.method(10); GenericInterfaceImpl2<Double> gi3 = new GenericInterfaceImpl2<>(); gi3.method(8.8); } } 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值