【问题标题】:Why can you not use an initializer block for a static variable in an inner class? [duplicate]为什么不能对内部类中的静态变量使用初始化程序块? [复制]
【发布时间】:2015-09-22 19:43:35
【问题描述】:

为什么 java 不允许在非静态内部类中使用静态初始化块进行静态声明?

在下面的代码中,outer2 会起作用,而 inner2 不会,尽管做了同样的事情。有任何想法吗?我不是在寻找解决方法,我只是想了解为什么 java 无法做到这一点。

public class WhyUNoStatic {
    public static final String outer1 = "snth";  // ok
    public static final String outer2;  // ok
    static
    {
        outer2 = "snth";
    }

    public class Inner {
        public static final String inner1 = "snth";  // still ok! 
        public static final String inner2;  // FAILURE TIME
        static
        {
            inner2 = "snth";
        }
    }
}

编辑:注意inner1 可以正常工作。并不是说 java 禁止内部类中的静态变量,它只是禁止声明它们。

【问题讨论】:

  • 因为内部类不能有static非最终成员,而static { }是静态成员。也许?
  • Java 禁止内部类中的非常量变量。 inner1 是一个常量变量。 inner2 不是。

标签: java static declaration inner-classes


【解决方案1】:

JLS, Section 8.1.3,不允许这种行为。

如果内部类声明了静态初始化器(第 8.7 节),则会出现编译时错误。

如果内部类声明了显式或隐式静态成员,则这是编译时错误,除非该成员是常量变量(第 4.12.4 节)。

你在你的内部类中声明了你的static 变量final,这没关系,但是那里禁止使用静态初始化器。

【讨论】:

  • 而至于原因,它可能会使已经相当复杂的初始化序列更加复杂。
  • 是的,这就是我想要达到的目的。为什么编译器不能处理这个?我很想看一个代码示例来说明为什么编译器很难处理这个问题......
【解决方案2】:

JLS Chapter 8

内部类不能声明静态初始化器(第 8.7 节)或成员接口,否则会发生编译时错误。

您可以改为声明一个嵌套类

public static class Inner {...}

【讨论】:

    猜你喜欢
    • 2014-04-13
    • 2014-10-16
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2022-08-06
    • 1970-01-01
    相关资源
    最近更新 更多