user_mda
user_mda

Reputation: 19378

Using a generic interface as a return type in java

Hello I have the following interface and two objects imepleting it in the following way

public interface MyObject<T> {
  T getId();
  String getName();
}

public class ObjectA implements MyObject<Integer> {
  @Override
  public Integer getId() {
    return 0;
  }

  @Override
  public String getName() {
    return "A";
  }
}

public class ObjectB implements MyObject<Long> {
  @Override
  public Long getId() {
  return 0;
 }

  @Override
  public String getName() {
    return "B";
  }

}

I want to create another interface that declares a method returning an object of type MyObject

public interface AnotherObject {
  public MyObject<?> getmyObject();
}

Is this the correct way to use a generic type object as the return type?

Upvotes: 0

Views: 1866

Answers (1)

rgettman
rgettman

Reputation: 178243

As you've written the interface AnotherObject, it will compile. But the wildcard means that any type parameter can be returned. Getting the MyObject object and calling getId on it must return an Object, which isn't very useful.

You can define the type parameter T on the interface, and it will be in scope on the return type of getMyObject, where you can refer to it.

public interface AnotherObject<T> {
    public MyObject<T> getMyObject();
}

This way, the MyObject can return a type of T. In practice, you may have AnotherObject<Integer> that can return a MyObject<Integer> whose getId() method returns an Integer instead of an Object.

Upvotes: 1

Related Questions