其他分享
首页 > 其他分享> > 泛型接口的定义与使用

泛型接口的定义与使用

作者:互联网

练习:
1.定义一个泛型接口generator

package generics.genericsinterface;

public interface generator<T> {
    T getMessage();
}

2.定义一个普通类A实现generator

package generics.genericsinterface;

public class A implements generator<String> {
    @Override
    public String getMessage() {
        return "This is from A";
    }
}

3.定义一个泛型类B<T,E>实现generator

package generics.genericsinterface;

public class B<T,E> implements generator<T> {
    private T key;
    private E value;

    public B(T key, E value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public T getMessage() {
        return key;
    }

    public E getValue(){
        return value;
    }
}

4.验证练习的正确性

package generics.genericsinterface;

public class Test {
    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.getMessage());

        B<String, Integer> str = new B<String, Integer>("is B",20);
        System.out.println(str.getMessage());
        System.out.println(str.getValue()); 
    }
}

标签:定义,generator,genericsinterface,接口,getMessage,value,key,泛型,public
来源: https://www.cnblogs.com/CH0701/p/15141512.html