简体   繁体   中英

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?

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 .

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