java接口和参数类型

时间:2016-08-27 11:52:03

标签: java interface parameterized

我正在尝试使用接口参数化泛型类型,Eclipse告诉我类型abc()没有实现方法T。当然它没有实现,因为T是一个接口,程序将在运行时找出T实际上是什么。所以,如果有人能帮助我解决这个问题,我将非常感激。

我有类似的东西:

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>;
      }
}

1 个答案:

答案 0 :(得分:3)

如您所定义,T的类型为Object。你想要的是为编译器提供T实际上是myInterface类型的提示。您可以通过定义T扩展myInterface

来实现
class myClass<T> implements myClassInterface<T extends myInterface>{
       String myMethod(){
            T myType;
            return myType.abc();
       }
}
相关问题