如何在方法接口中返回泛型类型

时间:2012-09-03 05:36:23

标签: java

如何为接口定义泛型返回类型,以便它实现类可以有自己的返回类型?

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

2 个答案:

答案 0 :(得分:5)

尝试以下内容。

interface A<T> {

  T doSomething();
}

class ImplA implements A<SomethingElseA> {

  public SomethingElseA doSomething() {
    ...
  }
}

class ImplB implements A<SomethingElseB> {

  public SomethingElseB doSomething() {
    ...
  }
}

答案 1 :(得分: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();
    }
}