humansg
humansg

Reputation: 715

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

Upvotes: 1

Views: 117

Answers (2)

Adam
Adam

Reputation: 36743

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

Upvotes: 1

obataku
obataku

Reputation: 29656

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() {
    ...
  }
}

Upvotes: 5

Related Questions