Julian
Julian

Reputation: 483

java enums but like public static final int?

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.

Upvotes: 3

Views: 2373

Answers (4)

assylias
assylias

Reputation: 328598

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;
}

Upvotes: 3

luketorjussen
luketorjussen

Reputation: 3264

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;
    }
}

Upvotes: 2

Rohit Jain
Rohit Jain

Reputation: 213223

If you really want to use Enum, then you can override toString() method in your enum, to get the value printed when you print your Enum Instance: -

enum Example {
    A(1), B(2);

    private int val;

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

    @Override
    public String toString() {
           switch (this) {
             case A:
                  return String.valueOf(val);

             case B:
                  return String.valueOf(val);

            }
            return super.toString();
    }
}

public class D {
    public static void main(String[] args) {    

        Example a = Example.A;
        Example b = Example.B;

        System.out.println(a);  // Prints 1
        System.out.println(b);  // Prints 2
    }
}

Ideally your above enum is just like the below class: -

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

So, I don't see the necessity of using Enums..

Upvotes: 0

ddekany
ddekany

Reputation: 31112

I think the shortest solution is:

public static final int A = 1, B = 2, C = 3;

Upvotes: 1

Related Questions