2012-09-03 153 views
1

如何爲接口定義泛型返回類型,以便它的實現類可以擁有自己的返回類型?如何在方法接口中返回泛型類型

public interface A { 
    public <T> T doSomething();  
} 


public class ImplA implements A { 
    public SomethingElseA doSomething() { 
     return obj.doSomething(); 
    } 
} 

public class ImplB implements A { 
    public SomethingElseB doSomething() { 
     return obj.doSomething(); 
    } 
} 
+0

'do'不是有效的標識符。 – oldrinb

+0

編輯爲'doSomething' – humansg

+0

現在應該沒問題吧? – MaVRoSCy

回答

5

請嘗試如下。

interface A<T> { 

    T doSomething(); 
} 

class ImplA implements A<SomethingElseA> { 

    public SomethingElseA doSomething() { 
    ... 
    } 
} 

class ImplB implements A<SomethingElseB> { 

    public SomethingElseB doSomething() { 
    ... 
    } 
} 
1

我猜你的意思是這樣嗎?我將do()更改爲foo(),因爲它是保留字...

public interface A<T> { 
    public T foo();  
} 

public class ImplA implements A<SomethingElseA> { 
    @Override 
    public SomethingElseA foo() { 
     return obj.doSomething(); 
    } 
} 

public class ImplB implements A<SomethingElseB> { 
    @Override 
    public SomethingElseB foo() { 
     return obj.doSomething(); 
    } 
}