Java接口通用类型

Java接口通用类型

本文介绍了Java接口通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



接口:

  public interface TestInterface< E> {
public void doSomething(E elem);

Class:

  public class TestClass implements TestInterface< E> {
public static void main(){
// ...
}
public void doSomething(E elem){
// ...
}
}

当我运行javac编译器时。我得到这些错误:

  TestClass.java:5:找不到符号
符号:class E
公共类TestClass实现TestInterface< E> {
^
TestClass.java:11:找不到符号
符号:class E
location:class TestClass
public void doSomething(E elem){
^

如果我用ieString替换所有的E ,但我希望它使用泛型类型。如何做到这一点?

解决方案

创建 TestClass 时,您需要传递 E ,如下所示

  public class TestClass implements TestInterface< ;字符串> {
public static void main(){
// ...

}
public void doSomething(String elem){
// .. 。
}
}

或者您需要制作 TestClass as generic

  public class TestClass< E>实现TestInterface< E> {
public static void main(){
// ...

}
public void doSomething(E elem){
// .. 。
}
}


Never used Java before and trying to implement an interface in a class:

Interface:

public interface TestInterface<E> {
        public void doSomething(E elem);
}

Class:

public class TestClass implements TestInterface<E> {
    public static void main() {
        // ...
    }
    public void doSomething(E elem) {
        // ...
    }
}

When I run the javac compiler. I get these errors:

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) {
                              ^

If I replace all the "E"'s with i.e. "String", it will work, but I want it to use generic types. How do I do this?

解决方案

When creating TestClass you need to pass what is E, something like below

public class TestClass implements TestInterface<String> {
    public static void main() {
        // ...

    }
    public void doSomething(String elem) {
        // ...
    }
}

or you need to make TestClass as generic

public class TestClass<E> implements TestInterface<E> {
     public static void main() {
            // ...

     }
     public void doSomething(E elem) {
            // ...
     }
}

这篇关于Java接口通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 05:33