【Java】定義和使用含有泛型的接口

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

 

含有泛型的接口的第一種使用方式:定義接口的實現類,實現接口,指定接口的泛型

public interface Interator<E>{

               E next();

}

 

//Scanner類實現了Iterator接口,並指定接口的泛型爲String,所以重寫的next方法泛型默認就是String

public final class Scanner implements Iterator<String>{

 

 

}

含有泛型的接口第二種使用方式:

接口使用什麼泛型,實現類就使用什麼泛型,類跟着接口走

就相當於定義了一個含有泛型的類,創建對象的時候確定泛型的類型

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){}

}

1.

package Generic;

public class DemoGenericInterface {
    public static void main(String[] args) {
        GenericInterfaceImpl ge = new GenericInterfaceImpl();
        ge.method("String泛型");

        GenericInterfaceImpl2<Integer> ge2 = new GenericInterfaceImpl2();
        ge2.method(2423);

        GenericInterfaceImpl2<Double> ge3 = new GenericInterfaceImpl2<>();
        ge3.method(53.8);
    }
}

2.

package Generic;

public interface GenericInterface<I>{
    public abstract void method(I i);

}

 

3.

package Generic;

import test.GenericClass;

public class GenericInterfaceImpl implements GenericInterface<String>{
//第一種實現方法
    @Override
    public void method(String s) {
        System.out.println(s);
    }
}

4.

package Generic;

public class GenericInterfaceImpl2<E> implements GenericInterface<E>{
    //第二種實現方法
    @Override
    public void method(E e) {
        System.out.println(e);
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章