Search code examples
javainterfaceparameterized

java interfaces and parameters types


I'm trying to parameterize a generic type with an interface and Eclipse tells me that method abc() is not implemented for the type T. Of course it is not implemented since T is an interface, the program will figure out at runtime what T really is. So, if anyone could help me solve this, I would be really appreciate.

I have something like:

interface myInterface {
    String abc();
}

class myClass<T> implements myClassInterface<T> {
    String myMethod() {
        T myType;
        return myType.abc();   // here it says that abc() is not implemented for the type T
    }
}

public class Main{
      public static void Main(String[] arg) {
         myClassInterface<myInterface> something = new myClass<myInterface>;
      }
}

Solution

  • As you have defined it T is of type Object. What you want instead is giving the compiler the hint that T is actually a type of myInterface. You do that by defining that T extends myInterface:

    class myClass<T> implements myClassInterface<T extends myInterface>{
           String myMethod(){
                T myType;
                return myType.abc();
           }
    }