简体   繁体   中英

How to return generic type in a method interface

How to define a generic return type for an interface, so that it's implementing class can have a return type of its own?

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

Try something as follows.

interface A<T> {

  T doSomething();
}

class ImplA implements A<SomethingElseA> {

  public SomethingElseA doSomething() {
    ...
  }
}

class ImplB implements A<SomethingElseB> {

  public SomethingElseB doSomething() {
    ...
  }
}

I'm guessing you mean like this? I changed do() to foo() as do is a reserved word...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM