user1121487
user1121487

Reputation: 2680

Java interface generic type

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?

Upvotes: 2

Views: 3238

Answers (1)

sanbhat
sanbhat

Reputation: 17622

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) {
            // ...
     }
}

Upvotes: 6

Related Questions