I’m experiencing an interesting discrepancy between what Eclipse and my JDK considers legal java.
Eclipse compiles the following class without a hitch, while the JDK on Mac OS X produces the error included below.
public class Builder {
private class Item {}
public void addItem(Item i) {}
public static void main(String[] args) {
new Builder() {{
addItem(new Item());
}};
}
}
$ javac Builder.java
Builder.java:9: non-static variable this cannot be referenced from a static context
addItem(new Item());
^
1 error
Making the Item class static resolves the problem, but it left me a bit curious: Is Eclipse being lenient and compiling code that is not actually valid? Did I stumble upon an eccentricity of the Mac OS X JDK? Am I missing something?
Update
Might be relevant to include the following
$ java -version
java version "1.6.0_33"
Java(TM) SE Runtime Environment (build 1.6.0_33-b03-424-11M3720)
Java HotSpot(TM) 64-Bit Server VM (build 20.8-b03-424, mixed mode)
Update 2
Making the Item more visible (default, protected or public) also satisfies the JDK compiler.
javac 1.7.0_04 compiles the source without error, so I’d suggest this is a bug in javac 1.6.