我尝试声明一个类,如下所示
class Outer{
private final class Inner{
public static final String s1 = new String("123");
public static final byte[] bytes = new byte[]{0x00, 0x01};
public static final String s2 = "123";
public static final byte byte1 = 0x02;
}
}
在上面的代码中,s1 和 bytes 无法编译,但 s2 和 byte1 可以编译。如果我将整个常量声明放在外部类中,它就可以正常工作。我错过了什么。有帮助吗?
最佳答案
阅读 Java 语言规范,第 3 版,§8.1.3。
An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces.
这就是为什么你不能声明 new public static final String s1 = new String("123");
。
Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).
这解释了为什么您可以执行 public static final String s2 = "123";
静态嵌套类可以有静态成员。
关于java - 无法在内部类中声明 Public static final String s = new String ("123"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4725505/