无法在内部类中声明Public static final String s = new String(" 123")

无法在内部类中声明Public static final String s = new String(" 123")

问题描述:

我试图声明如下所示的课程

I tried to declare a class as shown below

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和字节不会编译但是s2和byte1编译。如果我将整个常量声明放在外部类中它可以正常工作。我错过了什么有什么帮助吗?

In the above code s1 and bytes wont compile but s2 and byte1 compile. If I put the whole constant declaration in outer class it works fine. what am i missing. Any help?

阅读Java语言规范,第3版,§8.1.3。

Read Java Language Specification, 3rd ed, §8.1.3.


内部类是一个嵌套类,它没有显式或隐式地声明为
static。内部类可能不会声明静态初始化器(第8.7节)或
成员接口。

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);

This is why you cannot declare new public static final String s1 = new String("123");.


内部类可能不会声明静态成员,除非它们是编译时
常量字段(第15.28节)。

Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

这解释了为什么你可以做 public static final String s2 =123;

This explains why you can do public static final String s2 = "123";

静态嵌套类可以有静态成员。

A static nested class can have static members.