简体   繁体   English

Java编译器错误解惑:“内部类不能有静态声明” - 除了简单类型

[英]Java Compiler error puzzler: “inner classes cannot have static declarations” - except for simple types

While coding, I have encountered a strange Java Compiler behaviour. 编码时,我遇到了一个奇怪的Java编译器行为。

When compiling the class (source below), the compiler emits an error (" inner classes cannot have static declarations ") on the NULL class variable. 在编译类(下面的源代码)时,编译器会在NULL类变量上发出错误(“ inner classes cannot have static declarations ”)。 This is as expected! 这是预期的!

However, no error is generated on the ZERO class variable. 但是,ZERO类变量不会生成错误。 This I don't understand! 这个我不明白!

Why this difference, which seems to allow static declarations of simple types, but not Objects, in inner classes. 为什么这种差异似乎允许内部类中的简单类型而不是对象的静态声明。

(javac -version: 1.6.0_24) (javac -version:1.6.0_24)

public class Outer {
    public static final Runnable HELLO = new Runnable() {
        // No compiler error
        public static final int ZERO = 0;

        // Causes compiler error: "inner classes cannot have static declarations"
        public static final Object NULL = null;

        @Override
        public void run() {
            System.out.println("Hello " + ZERO + NULL);
        }
    };
}

问题是内部类不能有一个静态初始化块,这是初始化非平凡常量和非常量所必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Android Parcelable类-内部类不能具有静态声明 - Android Parcelable Class - Inner classes cannot have static declarations RecyclerView:内部类不能有静态声明 - RecyclerView: Inner classes cannot have static declaration Java性能难题:包装器类比原始类型更快? - Java performance puzzler: wrapper classes faster than primitive types? Java外部和内部类的方法名称相同:非静态方法静态上下文错误 - Java outer and inner classes have method with the same name: non-static method static context error Java 中的内部类 - 非 static 变量错误 - Inner classes in Java - Non static variable error Java中的内部静态类 - Inner static classes in java 为什么编译器无法推断 Java 中内部 class 的泛型类型? - Why compiler cannot infer generic types of the inner class in Java? Java私有静态最终字段和匿名内部类与Kotlin const val和对象表达式/声明 - Java private static final field and anonymous inner classes vs. Kotlin const val and object expressions/declarations 为什么我只有在拥有内部类时才能获得“无法从静态上下文引用的非静态变量”错误? - Why do I get the “non-static variable this cannot be referenced from a static context” error only when I have inner classes? 方法本地类中的Java final静态声明 - Java final static declarations in method local classes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM