Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java enums but like public static final int?

Tags:

java

I want to have a list of constants like A, B, C related to integers 1, 2, 3

I know you can do like

class Example {
    public static final int A = 1;
    etc...
}

and

enum Example {
    A(1), ... etc;
    some initialization of an integer
}

But is there a way to do it like the public static final but as succinct as enums? When I use A and I really mean 1 I don't want to call Example.A.value or something like that.

like image 961
Julian Avatar asked Feb 19 '26 21:02

Julian


2 Answers

One way would be to use an interface, where variables are public, static and final by default:

interface Example {
    int A = 1;
    int B = 2;
}
like image 182
assylias Avatar answered Feb 21 '26 12:02

assylias


If I understand what you're asking correctly, you want to do something like this:

enum Example {
    A = 1,
    B = 2,
    ....
}

There is no nice simple syntax for this.

You either have to write out some constants:

public interface Example {
    public static final int A = 1;
    public static final int B = 2;
    ....
}

...Or you can add some other value to the enum:

public enum Example {
    A(1),
    B(2)
    ....

    private final int val;

    public Example (int val) {
        this.val = val;
    }

    public int getValue() {
        return val;
    }
}
like image 20
luketorjussen Avatar answered Feb 21 '26 11:02

luketorjussen



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!