Enums
- An enum type is a special data type that enables for a variable to be a set of predefined constants
- Enums should be used any time one needs to represent a fixed set of constants.
More Info on Enums
- The enum declaration defines a class (called an enum type). The enum class body
can include methods and other fields. The compiler automatically adds some
special methods when it creates an enum. For example, they have a static
values
method that returns an array containing all of the values of the enum in the order they are declared. - All enums implicitly extend
java.lang.Enum
. Because a class can only extend one, the Java language does not support multiple inheritance of state, and therefore an enum cannot extend anything else. - The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself.
Why Enumerations?
- Way of naming things – It’s real
easy to identify things. We do not need to use a collection to store data.
- Type Safe – We can’t compare to a
wrong type. Which can happen with Strings.
- Limits Input – if we could
restrict the input coming into the method, things can become quite easier.
- Groups things into a Set
- Iterable - if utilized properly, then unnecessary if conditions and switch cases can be avoided
When to use Enumeration?
- As much as possible
- Anytime constraining input is beneficial
- In place of string constants
- In place of integers used as types – for eg month. Using integers to identify months. Can be easily done if we store them as enums
Enumerations Are Classes
Enums are full functional classes
- It gives us a values method
- Constructor – every enum has a default constructor, but we can add parameterized constructors
- Members
- Use it as a Singleton
- Use it as a Factory
I have demonstrated the below concepts on my github repo
- Usage of basic Enum
- Using Enum as a Singleton
- Using Enum as a Factory
The link to the github repo is below
https://github.com/omerhashmininjago/java-programs/tree/master/src/main/java/com/demonstrate/concepts/enumerations
No comments:
Post a Comment