无法在内部类中声明Public static final String s = new String(" 123") [英] Cannot declare Public static final String s = new String("123") inside an inner class

查看:145
本文介绍了无法在内部类中声明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.

这篇关于无法在内部类中声明Public static final String s = new String(" 123")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆