I have often the situation where I need a variable for a class that could be represented as simple enum type, for example:
private enum PageOrder {DOWN_THEN_OVER, OVER_THEN_DOWN};
If a declare the enum type within the class that holds the variable then I have to use the qualified name MyClass.PageOrder
which is not comfortable.
But if I create a new class I have a class for just a simple enum declaration, which seems overkill for me.
For that reason, I frequently use integers instead of enum type.
Any comments/suggestions on this topic?
Because they are constants, the names of an enum type's fields are in uppercase letters. You should use enum types any time you need to represent a fixed set of constants.
Enums are exactly final inner classes that extends java. lang. Enum<E> . You cannot extend, override or inherit an enum .
All Enums are implicitly static, its just you don't need to write the static keyword.
You can do
import static yourpkg.MyClass.PageOrder;
This will always work since inner enums are always static. Note that this works even in the file that defines the MyClass
class.
For that reason, I frequently use integers instead of enum type.
Please don't do that.
You can often choose a name for the parent class and the enum
that actually helps the clarity of the code.
class Page {
enum Order {
DOWN_THEN_OVER, OVER_THEN_DOWN;
}
}
// Accessing: A little verbose but clear and efficient.
Page.Order order = Page.Order.DOWN_THEN_OVER;
You can also static import
each enum
you use but I prefer the verbosity above.
import static com.oldcurmudgeon.test.Test.Order.DOWN_THEN_OVER;
import static com.oldcurmudgeon.test.Test.Order.OVER_THEN_DOWN;
public class Test {
enum Order {
DOWN_THEN_OVER, OVER_THEN_DOWN;
}
public void test() {
Order pageOrder = DOWN_THEN_OVER;
}
}
Obviously you cannot take this approach if the enum
is private
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With