开发者

Problem with ENUM in eclipse

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 开发者_如何学Cplease?

Thanks :)


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.


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());

    }

}


Try it the other way around:

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

    private Enun(final int i) {
    }
}

This has the side-effect that now STATIK is not a compile-time-constant anymore, but there are little locations this matters (usage in switch statements - but there you should use your enum values).


You cannot pass STATIK in constructor, If you want to achieve this use something like

public enum Enun {
    A(1);
    private int someInt;

    private Enun(final int i) {
        this.someInt = i;
    }
}

Remember enum is a singleton by default, so no need to use static for this int.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜