Following two cases seem to work:
public class A {
private class B {
public static final String str = "str";
}
}
public class A {
private static class B {
public static final String str = new String("str");
}
}
But Following gives an error as specified in comment:
public class A {
private class B {
//The field str cannot be declared static;
//static fields can only be declared in static or top level types
public static final String str = new String("str");
}
}
Why it is allowed in first two cases and why it is causing issue in last one?
This is required by the JLS, section 8.1.3. I never saw a reason for it, but I suspect that an inner class that is not static requires an instance of the outer class, but declarations as static break that concept, and by allowing them it would create a whole other set of rules to handle just that case, which was deemed not worth it. Whereas when it is static, it is really just like any other class, that just happens to be in the same source file.