When reading this question, I open my editor to try some code samples to verify and understand it. The following is my code:
public enum EnumImpl {
B {
public void method() {
System.out.println(s); //(1)non-static variable s cannot be referenced from a static context
}
public static int b; //(2)Illegal static declaration in inner class
};
private int s;
}
But compiling the upper code makes me more confused.
- The first error comes from what upper question shows that
B
actually belong to a static class. So inmethod
, it is a static context. - The second error, by contrast, says that here is a inner class -- non-static nested class as java doc says.
- The following is a line I cited from JLS, but it seems a little bit confusing and vague.
A nested enum type is implicitly static.
The following is the byte code of anonymous synthetic class of B:
final class enum_type.EnumImpl$1 extends enum_type.EnumImpl { enum_type.EnumImpl$1(java.lang.String, int); Code: 0: aload_0 1: aload_1 2: iload_2 3: aconst_null 4: invokespecial #1 // Method enum_type/EnumImpl."<init>":(Ljava/lang/String;ILenum_type/EnumImpl$1;)V 7: return public void method(); Code: 0: return }
So the class of B is static or not?
@Lew Bloch seems saying it is like the following (the behavior matches with above enum example, but if this is true, the answer of the linked question is wrong in some senses).
abstract class Cmp {
private int s;
static {
class Bclass extends Cmp {
public void method() {
// System.out.println(s);
}
// private static int b;
}
}
}