fork download
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3.  
  4. class CovarianceTest {
  5. public static void main(String[] args) {
  6. Alpha alpha = new Alpha();
  7.  
  8. // Type mismatch: cannot convert from element type capture#1-of ?
  9. // extends CovarianceTest.Data to CovarianceTest.Beta
  10. // Quick fix: Change type of beta to Beta.
  11. // That would work, but nasty type casting.
  12. for (Beta beta : alpha.getChildren()) {
  13. System.out.println(beta.getID());
  14. }
  15. }
  16.  
  17. public static abstract class Data {
  18. public abstract Collection<? extends Data> getChildren();
  19. }
  20.  
  21. public static class Alpha extends Data {
  22. public Collection<Beta> children;
  23.  
  24. public Alpha() {
  25. this.children = new ArrayList<Beta>();
  26. this.children.add(new Beta(1));
  27. this.children.add(new Beta(2));
  28. this.children.add(new Beta(3));
  29. }
  30.  
  31. @Override
  32. public Collection<Beta> getChildren() {
  33. return this.children;
  34. }
  35. }
  36.  
  37. public static class Beta extends Data {
  38. private int id;
  39.  
  40. public Beta(int id) {
  41. this.id = id;
  42. }
  43.  
  44. @Override
  45. public Collection<Data> getChildren() {
  46. return null;
  47. }
  48.  
  49. public int getID() {
  50. return this.id;
  51. }
  52. }
  53. }
Success #stdin #stdout 0.1s 320576KB
stdin
Standard input is empty
stdout
1
2
3