在Java中,泛型接口的实现与普通接口的实现类似,只是在实现时需要指定泛型类型参数。下面是一个简单的泛型接口及其实现的例子:
MyGenericInterface:public interface MyGenericInterface<T> {
void add(T item);
T get(int index);
}
这里,T是一个泛型类型参数,它将在实现接口的类中被具体的类型替换。
MyGenericClass:public class MyGenericClass<T> implements MyGenericInterface<T> {
private List<T> items;
public MyGenericClass() {
items = new ArrayList<>();
}
@Override
public void add(T item) {
items.add(item);
}
@Override
public T get(int index) {
return items.get(index);
}
}
在这个例子中,MyGenericClass类实现了MyGenericInterface接口,并指定了泛型类型参数T。这样,MyGenericClass类就可以根据需要使用不同的类型来实例化。
public class Main {
public static void main(String[] args) {
// 使用Integer类型实例化MyGenericClass
MyGenericInterface<Integer> intList = new MyGenericClass<>();
intList.add(1);
intList.add(2);
System.out.println("Integer 0: " + intList.get(0));
// 使用String类型实例化MyGenericClass
MyGenericInterface<String> strList = new MyGenericClass<>();
strList.add("Hello");
strList.add("World");
System.out.println("String 1: " + strList.get(1));
}
}
这个例子展示了如何使用不同的类型(如Integer和String)来实例化泛型类MyGenericClass,并实现泛型接口MyGenericInterface。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。