Problem with ENUM in eclipse

My Eclipse IDE has the following error:

You cannot refer to a field before defining it

I am trying to use the 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) {
    }
}

Can someone tell me how can I solve this problem please?

Thank:)

+3
source share
4 answers

You cannot extend anything else, because an enumeration extends something already (according to the specification), but you CAN implement with an enumeration! try it

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

    }

}
+3
source

Yes, you cannot reference static members of an enumeration in an enumeration declaration. If you want to name these numbers, you must make STATIK a member of the nested static class:

A(Constants.STATIK);

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

private Enun(final int i) {
}

- , , aditional.

+5

:

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

    private Enun(final int i) {
    }
}

This has a side effect that STATIK is no longer a compile-time constant, but there are few places in it (use in switch statements, but there you have to use your enum values).

+1
source

You cannot pass STATIK in the 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 that the default enum is singleton, so there is no need to use static for this int.

0
source

Source: https://habr.com/ru/post/1793431/


All Articles