2016-08-27 47 views
-1

我想用接口參數化泛型,Eclipse告訴我方法abc()沒有實現類型T。當然,由於T是一個接口,因此它不會實現,程序會在運行時計算出真正的T。所以,如果有人能幫我解決這個問題,我會非常感激。java接口和參數類型

我有這樣的:當你已經將它定義TObject

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

哪裏定義myClassInterface? –

+0

T是一個通用類型。與界面的連接在哪裏? –

+0

[有界泛型類型](https://docs.oracle.com/javase/tutorial/java/generics/bounded.html)是你需要的 –

回答

3

。你想要的是給編譯器提示T實際上是一種myInterface。你這樣做,通過定義T擴展myInterface

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

我試過了:class myClass implements myClassInterface 它工作正常。謝謝 ! – Lexy