Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with ENUM in eclipse

Tags:

java

enums

I have the the following error in my eclipse IDE:

Cannot reference a field before it is defined

I try to use an enum variable and some of its values have the same name.

public enum Enun {
    A(STATIK);
    private static int STATIK = 1;

    private Enun(final int i) {
    }
}

Could anyone tell me how I can solve this problem please?

Thanks :)

like image 368
Sergio Avatar asked Feb 13 '26 11:02

Sergio


2 Answers

Yeah, you can't reference static members of the enum in the enum declaration. If you want to name these numbers, then you should make the STATIK a member of a nested static class:

A(Constants.STATIK);

private static class Constants {
    private static int STATIK = 1;
}

private Enun(final int i) {
}

Although I would question the need for this - the enum name should tell you all you need to know about those numbers, and you shouldn't need an aditional static declaration.

like image 149
Yishai Avatar answered Feb 15 '26 11:02

Yishai


You can't extend anything else because enum extends something already (by specification) but you CAN implement with an enum! Try this

public interface EnunConstants {
    int STATIK = 1;
    int AWESOME = 2;
    int POSSUM = 3;

}

public enum Enum implements EnunConstants {
    A(STATIK),
    B(AWESOME),
    C(POSSUM);

    private int val;

    private Enun(final int i) { this.val = i; }
    public int getVal() { return val; }

}

public class Sergio {

    public static void main(String[] args) {
        Enun S = Enun.A;
        System.out.println(S.getVal());
        Enun P = Enun.C;
        System.out.println(P.getVal());

    }

}
like image 29
corsiKa Avatar answered Feb 15 '26 13:02

corsiKa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!