定义和使用含有泛型的接口
生活随笔
收集整理的這篇文章主要介紹了
定义和使用含有泛型的接口
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
含有泛型的接口
定義格式:
修飾符 interface接口名<代表泛型的變量> { }例如,
public interface MyGenericInterface<E>{public abstract void add(E e);public abstract E getE(); }使用格式:
1、定義類時確定泛型的類型
例如
public class MyImp1 implements MyGenericInterface<String> {@Overridepublic void add(String e) {// 省略...}@Overridepublic String getE() {return null;} }此時,泛型E的值就是String類型。
2、始終不確定泛型的類型,直到創建對象時,確定泛型的類型
例如
public class MyImp2<E> implements MyGenericInterface<E> {@Overridepublic void add(E e) {// 省略...}@Overridepublic E getE() {return null;} }確定泛型:
/** 使用*/ public class GenericInterface {public static void main(String[] args) {MyImp2<String> my = new MyImp2<String>(); my.add("aa");} } package com.learn.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);} } package com.learn.demo03.Generic; /*定義含有泛型的接口*/ public interface GenericInterface<I> {public abstract void method(I i); } package com.learn.demo03.Generic; /*含有泛型的接口,第一種使用方式:定義接口的實現類,實現接口,指定接口的泛型public interface Iterator<E> {E next();}Scanner類實現了Iterator接口,并指定接口的泛型為String,所以重寫的next方法泛型默認就是Stringpublic final class Scanner implements Iterator<String>{public String next() {}}*/ public class GenericInterfaceImpl1 implements GenericInterface<String>{@Overridepublic void method(String s) {System.out.println(s);} } package com.learn.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> {@Overridepublic void method(I i) {System.out.println(i);} }?
總結
以上是生活随笔為你收集整理的定义和使用含有泛型的接口的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 定义和使用含有泛型的方法
- 下一篇: 泛型通配符