[英]Two implementations for an interface with different types - Is this not possible?
[英]interface implementations with different concrete types as method parameters
我想在接口中有一个接受任何类型的通用对象的方法,比如
public void myMethod(List<?>);
现在实现应该只接受某种类型,例如。 实现1:
public void myMethod(List<Integer>);
实施2:
public void myMethod(List<String>);
但是这不起作用public void myMethod(List<Integer>);
不是public void myMethod(List<?>);
的有效实现public void myMethod(List<?>);
我怎么能实现这个目标? (除了使用对象参数,因此依赖于转换并手动进行类型检查)
除非我遗漏了一些明显的东西(这对我的喜好太多了),为什么不让界面本身通用呢?
public interface MyInterface<T> {
public void myMethod(List<T> list);
}
哪个可以像这样实现:
public class MyClass<T> implements MyInterface<T> {
@Override
public void myMethod(List<T> list) {
// TODO complete this!
}
}
并使用如下:
public class Foo {
public static void main(String[] args) {
MyClass<String> myString = new MyClass<String>();
MyClass<Integer> myInt = new MyClass<Integer>();
}
}
你可能想要你的类型: http : //docs.oracle.com/javase/tutorial/java/generics/gentypes.html
例如,使用public void myMethod(List<T>);
对于您的界面,然后您的具体类使用您想要的类型进行实例化。 `
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.