by jhdevos · 9y ago · 0 comments
As for the problem itself: it really has nothing to do with inner classes (they are static in the example!). The problem is with this line:
Constrain<U,? super T> constrain = null;
which leads the type system to assume that there is a type that is a superclass of T, which also is a subclass of B (from the 'Constrain' class) - even though no such type could possibly exist! The evil trick is in the 'null' - even though a type with the stated constraints is impossible, and so no actual 'real' value of this generic type could exist, 'null' is part of all types, so the compiler can't see the problem.It really is a problem in the type system as defined in the standard, not just a compiler bug.
static class Constrain<A, B extends A> {}
reads as for all propositions A and B, such that B implies A, proposition Constrain<A, B> holds.
While, the line: Constrain<U,? super T> constrain = null;
kind of says: Admit that there exists type X, such that T implies X, for which Constrain<U, X> holds.
Even though no proof (read constructed instance) that X implies U is provided.If we look at concrete execution instance with String and Integer:
String implies Object, Serializable, Comparable<String>, CharSequence. None of those imply/extend Integer, which is required for truthful Constrain<U, ? super T> proposition.
Basically, ex falso quodlibet :)
EDIT: spacing, formatting, wording.
Section 4.5 in the language spec deals with parameterized types; 4.5.1 deals with wildcards. Of course, there is no example in the specs that clearly points out what happens in this example - otherwise this wouldn't have remained undiscovered for so many years :)
If you can show, using the rules in the spec, that the sample program shouldn't pass type checking, then you'll have proved the article wrong :-)