Why is java enumeration constant initialization incomplete?

I stumbled upon a very strange mistake. I can't explain why Imagine the following enumeration:

import java.awt.Color;

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(MyEnum.CONSTANT1.get());
        System.out.println(MyEnum.CONSTANT2.get());
    }

    private enum MyEnum {
        CONSTANT1(staticMethod1()),CONSTANT2(staticMethod2());

        private static final Color WHY_AM_I_NULL = new Color(255,255,255);

        private final Color color;

        private MyEnum(Color color) {
            this.color = color;
        }

        public Color get() {
            return color;
        }

        private static Color staticMethod1() {
            return new Color(100,100,100);
        }

        private static Color staticMethod2() {
            return WHY_AM_I_NULL;
        }
    }

}

The results of running these are:

java.awt.Color[r=100,g=100,b=100]
null

The question is, why is the second empty?

AMMENDMENT: if you set why_ AM_ I_ Null is placed in a private static class in the enumeration, then it will be initialized

Solution

The problem is that all static fields (and enumeration instances are counted in this way) are initialized in the order they are declared So when constant2 is instantiated, the field why_ AM_ I_ Null is still uninitialized (hence null)

Since you cannot place this field before enumerating instances, you must find some other way to perform the required operation (for example, placing the field outside the enumeration class) If you tell us what you really want to accomplish, you can make further suggestions

Edit: if when_ AM_ I_ If NULL is placed in a nested class, the fields of the class will be initialized when the class is first accessed (that is, during the execution of staticmethod2)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>