fork download
  1. import java.util.ArrayList;
  2. import java.util.Collection;
  3.  
  4. public 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. public Collection<? extends Data> getChildren() {
  32. return this.children;
  33. }
  34. }
  35.  
  36. public static class Beta extends Data {
  37. private int id;
  38.  
  39. public Beta(int id) {
  40. this.id = id;
  41. }
  42.  
  43. public Collection<? extends Data> getChildren() {
  44. return null;
  45. }
  46.  
  47. public int getID() {
  48. return this.id;
  49. }
  50. }
  51. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:4: error: class CovarianceTest is public, should be declared in a file named CovarianceTest.java
public class CovarianceTest {
       ^
Main.java:12: error: incompatible types: CAP#1 cannot be converted to Beta
		for (Beta beta : alpha.getChildren()) {
		                                  ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Data from capture of ? extends Data
2 errors
stdout
Standard output is empty