泛型接口的使用

来源:互联网 发布:网络授权书制作免费 编辑:程序博客网 时间:2024/06/07 03:15

1、定义泛型接口,并去实现这个接口:
接口类:GenericInterface.class

public interface GenericInterface<E> {    public abstract E print(E e);}

实现接口的类:GenericClass .class

public class GenericClass implements GenericInterface<Person>{    @Override    public Person print(Person e) {        e.setAge(e.getAge()*2);        e.setName("大"+e.getName());        return e;    }}

创建类对象:

public static void main(String[] args) {        GenericClass gc = new GenericClass();        Person p = new Person("憨妹妹",18);        System.out.println(p);        Person ps = gc.print(p);        System.out.println(ps);    }

输出:
Person [name=憨妹妹, age=18]
Person [name=大憨妹妹, age=36]


2、有些时候我们在定义一个类去实现泛型接口时,我们并不确定这个类将要实现哪种类型的类,这时我们就不能确定接口中的泛型,,那么接口中的泛型尚未确认,这时就要求这个类也必须定义泛型,而且泛型名称要一致,例程如下:
接口类:GenericInterface.class

public interface GenericInterface<E> {    public abstract E print(E e);}

实现接口的类:GenericClass .class

public class GenericClass<T> implements GenericInterface<T>{    @Override    public T print(T t) {        System.out.println(t.getClass());        return t;    }}

创建类对象:

public static void main(String[] args) {        //实现Person类对象        GenericClass<Person> gc = new GenericClass<Person>();        Person p = new Person("憨妹妹",18);        Person ps = gc.print(p);        System.out.println(ps);        //实现String类对象        GenericClass<String> gc1 = new GenericClass<String>();        String str = "憨妹妹";        String s = gc1.print(str);        System.out.println(s);    }

输出:
class com.huawei.generic.Person
Person [name=憨妹妹, age=18]
class java.lang.String
憨妹妹

0 0
原创粉丝点击