Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Options/enums in java?

Tags:

java

Is there a best practice for enumerations in java? For example, I have the following:

class Foo {

    public static final int OPTION_1 = 'a';
    public static final int OPTION_2 = 'b';

    public void doSomething(String name, int option) {
       ...
    }
}

void test() {
    Foo foo = new Foo();
    foo.doSomething("blah", Foo.OPTION_2);
}

so the user can choose to use one of the static ints defined in Foo, but they could also supply any other int they want, there's no compile-time checking on it. Is there some way around this in java, some other way of doing this to restrict the end developer to choose from only the defined option types?

Thanks

like image 640
user246114 Avatar asked Sep 01 '26 11:09

user246114


2 Answers

class Foo {
    public enum Option{First, Second}
    public void doSomething(String name, Option option) {
       ...
    }
}

void test() {
    Foo foo = new Foo();
    foo.dosomething("blah", Foo.Option.Second);
}
like image 152
Carl Manaster Avatar answered Sep 04 '26 02:09

Carl Manaster


Since Java 1.5 there is the enum keyword which makes typesafe enumerations

Your code would look like this then :

class Foo {

    public enum Option = { OPTION_1,  OPTION_2 };

    public void doSomething(String name, Option option) {
       ...
    }
}

void test() {
    Foo foo = new Foo();
    foo.doSomething("blah", Foo.Option.OPTION_2);
}

This is fully supported by the type system so the compiler will enforce the user not to become to creative when passing options.

You can read more here

like image 41
Peter Tillemans Avatar answered Sep 04 '26 00:09

Peter Tillemans



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!