Cannot declare Public static final String s = new String(“123”) inside an inner class

蹲街弑〆低调 提交于 2019-12-19 02:49:19

问题


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

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?


回答1:


Read Java Language Specification, 3rd ed, §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.

This is why you cannot declare 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).

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

A static nested class can have static members.




回答2:


cf Java Language specification, second edition, §8.1.2

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




回答3:


Inner classes were designed to work in the context of the outer class, I think static variables would break this rule.

8.1.2 Inner Classes and Enclosing Instances

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. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).




回答4:


try this, it works fine inside an inner class:

public static final String  s="123";

I don't know the reason why it is allowed.



来源:https://stackoverflow.com/questions/4725505/cannot-declare-public-static-final-string-s-new-string123-inside-an-inner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!