之前从未使用过Java并尝试在类中实现接口:
接口:
public interface TestInterface<E> {
public void doSomething(E elem);
}
类别:
public class TestClass implements TestInterface<E> {
public static void main() {
// ...
}
public void doSomething(E elem) {
// ...
}
}
当我运行javac编译器时。我收到这些错误:
TestClass.java:5: cannot find symbol
symbol: class E
public class TestClass implements TestInterface<E> {
^
TestClass.java:11: cannot find symbol
symbol : class E
location: class TestClass
public void doSomething(E elem) {
^
如果我用“String”替换所有“E”,它将起作用,但我希望它使用泛型类型。我该怎么做?
答案 0 :(得分:6)
创建TestClass
时,您需要传递E
,如下所示
public class TestClass implements TestInterface<String> {
public static void main() {
// ...
}
public void doSomething(String elem) {
// ...
}
}
或者您需要将TestClass
作为通用
public class TestClass<E> implements TestInterface<E> {
public static void main() {
// ...
}
public void doSomething(E elem) {
// ...
}
}