繁体   English   中英

如何将 static 字段初始化为 ZD52387880E1EA21817A792D371 中相同 class 的 object?

[英]How to initialize a static field as an object of the same class in Java?

I have a simple nested class A. (In C I would use a struct.) I want to provide a default object A.DEFAULT of class A without having to call the constructor each time. 所以我的想法是这样的:

class MyApplication {
   class A {
        int x;
        double y;
        public static final DEFAULT = new A(0, 0.0);

        public A(int x, double y) {
            this.x = x;
            this.y = y;
        }
    }
    …

显然,这不起作用,因为在加载 class 之前无法调用构造函数。

如何处理? e如何。 G。 Color.RED 处理这个?

这与构造函数调用无关,您只是犯了几个简单的错误。

您尚未为DEFAULT指定类型:

public static final A DEFAULT

如果没有MyApplication的实例,则无法实例化A ,因为A是内部 class:

new MyApplication().new A(0, 0.0);

但是,您可能不打算将A设为内部 class,因此我将其标记为static

除了你错过了DEFAULT定义中的类型( A )的明显问题......

问题不在于“class [未] 已加载”。 问题在于,在 Java 中,内部 class 的每个实例都隐含地引用了创建它的外部 class 的实例。 由于在初始化static字段时没有外部 class 的实例,因此会出现错误:

MyApplication.java:5: error: non-static variable this cannot be referenced from a static context
        public static final A DEFAULT = new A(0, 0.0);
                                        ^

除了最新的 Java 版本之外,即使在非静态内部 class 内声明一个static字段都是非法的,无论你给它什么值:

MyApplication.java:5: error: Illegal static declaration in inner class MyApplication.A
        public static final A DEFAULT = new A(0, 0.0);
                              ^
  modifier 'static' is only allowed in constant variable declarations

解决方案是使内部 class没有对外部 class 的引用,您可以通过A声明为 static 来实现:

class MyApplication {
    static class A {
    ^^^^^^

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM