Return generic value from method : Generic Method « Generics « Java






Return generic value from method

import java.io.Serializable;

class Base {
}

class Sub1 extends Base implements Serializable {
  public void run() {
  }
}

class Sub2 extends Base implements Serializable {
  public void run() {
  }
}

public class TypeInference {
  static <T extends Base> T infer(T t1, T t2) {
    return null;
  }

  public static void main(String[] args) {
    Base base = infer(new Sub1(), new Sub2());
    Serializable runnable = infer(new Sub1(), new Sub2());
  }

}

 








Related examples in the same category

1.Demonstrate a simple generic method.Demonstrate a simple generic method.
2.Java generic: Ambiguity caused by erasure on overloaded methods.
3.Overriding a generic method in a generic class. Overriding a generic method in a generic class.
4.Java generic: A situation that creates a bridge method.Java generic: A situation that creates a bridge method.