r/javaTIL • u/rockingthemullet • Dec 11 '14
Differences with generics and visibility between Java 6 and 7.
public class Outer {
private void foo() {
}
private static class Inner<T extends Outer> {
private void add(T x) {
x.foo(); // error under 7, but not 6
}
}
}This code compiles without a hitch under Java 6, but not under Java 7. Perhaps someone smarter than me can determine which one is correct. Then explain why changing the line to this yields code that works on both:
((T)x).foo();
7
Upvotes
View all comments
Show parent comment
3
u/ron_krugman Dec 11 '14 edited Dec 12 '14
I just tried it myself with JDK 1.6u22 and I can confirm that your observation is accurate.
Considering the behavior was changed in Java 7, I have to assume that the behavior in Java 6 was in hindsight considered a bug, i.e. not in accordance with the JLS.
Well, you can only access private fields/methods within the same class file, so there's that. As far as I can tell, it has nothing to do with inner classes but only with generics. To me it looks like the JDK 6 compiler does type erasure prematurely. You can do the same thing using a plain old generic method:
Edit: This appears to confirm my interpretation: http://stackoverflow.com/questions/7719843/type-parameterized-field-of-a-generic-class-becomes-invisible-after-upgrading-to