Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a static field defined in an enum as an argument in the constructor

I have an enum and want to use a static value as the argument in the constructor.

public enum Enum
{
    e1(0),
    e2(1),
    e3(SPECIAL_VALUE);

    static int SPECIAL_VALUE = -1;

    int value;

    private Enum(int value)
    {
        this.value = value;
    }
}

In this example, SPECIAL_VALUE is accessed before it is initialized, so this clearly doesn't work. I was wondering if there was a common solution. Or a reason why I shouldn't need to do this.

NOTE: There's probably a duplicate out there somewhere, but everything I can find has to do with using a static field in the body of the constructor, not as an argument, and I don't think the solutions presented there are applicable.

like image 200
Mar Johnson Avatar asked Aug 15 '14 17:08

Mar Johnson


1 Answers

package test;

public enum Enum
{

    e1(0),
    e2(1),
    e3(SPECIAL_VALUE());

    static int SPECIAL_VALUE(){return -1;}

    int value;

    private Enum(int value)
    {
        this.value = value;
    }
    public int getValue()
    {
        return value;
    }

    public static void main(String args[])
    {
        System.out.println(e3.name());
        System.out.println(e3.getValue());
    }
}

tried ideone for the first time, voila! http://ideone.com/Bz1N69

like image 145
Kalpesh Soni Avatar answered Nov 05 '22 08:11

Kalpesh Soni