fork(1) download
  1. import java.util.*;
  2. import java.util.concurrent.atomic.AtomicInteger;
  3.  
  4. class Covariance {
  5. public static void main(String[] args) {
  6. X x = new X();
  7. x.getChildren().add(new Y());
  8. x.getChildren().add(new Y());
  9. Test test = new Test();
  10. test.methodTest(x);
  11. }
  12.  
  13. public static abstract class Data {
  14. public abstract Collection<? extends Data> getChildren();
  15. }
  16.  
  17. public static class Y extends Data {
  18. private static AtomicInteger idGen = new AtomicInteger();
  19.  
  20. public final int id = idGen.getAndIncrement();
  21.  
  22. public Collection<? extends Data> getChildren() {
  23. return null;
  24. }
  25.  
  26. @Override
  27. public String toString() {
  28. return String.format("Y [id=%s]", id);
  29. }
  30. }
  31.  
  32. public static class X extends Data {
  33. public final Collection<Y> ys = new ArrayList<>();
  34.  
  35. public Collection<Y> getChildren() {
  36. return ys;
  37. }
  38. }
  39.  
  40. public static class Test {
  41. public void methodTest(X someX) {
  42. for (Y y : someX.getChildren()) { //NOPE: type mismatch
  43. System.out.println(y);
  44. }
  45. }
  46. }
  47. }
Success #stdin #stdout 0.13s 320576KB
stdin
Standard input is empty
stdout
Y [id=0]
Y [id=1]