This might seem like a trivial question, but I'm a bit muddled in my thinking regarding enums..
So I have a class - let's say its called DVDPlayer - and I want to have an enum that represents whether it's ON, OFF, or STANDBY.
So I can put the enum in the class - it doesn't make sense outside of the class. My question is this - should the enum be public, so that other classes can query values, or should I make it private, and then have "isOn", "isOFf" and "isStandby" methods?
The latter sounds a bit daft, but I'm unsure as to whether it's a good idea to have the enum as public as well.
You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.
The Enum<T> generic base class provides quite a few convenient methods. Two frequently used among them are: String name(): Returns the name of the enum constant. int ordinal(): Returns the ordinal of this enumeration constant.
The main objective of enum is to define our own data types(Enumerated Data Types). Declaration of enum in Java: Enum declaration can be done outside a Class or inside a Class but not inside a Method.
Each item in a Java enum is called a constant, an immutable variable — a value that cannot be changed.
I would say it seems like a good idea to make it public. Main reason being that the application is easier to extend since you wouldn't have to think about adding new methods each time you add a state.
If you decide to make it public, you should consider having it as top-level enum. I don't really see why you say "it doesn't make sense outside of the class". I think a DVDPlayerState
sounds like a perfectly fine public / top-level enum.
It depends on how you want to use the DVDPlayer
class from the outside world:
if (dvdPlayer.getState() == State.ON)
or
if (dvdPlayer.isOn())
I think the first one is a better option. You don't have to pollute your code with delegating methods.
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