Sunday, 17 February 2019

Enumerations

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?

  1. Way of naming things – It’s real easy to identify things. We do not need to use a collection to store data.
  2. Type Safe – We can’t compare to a wrong type. Which can happen with Strings.
  3. Limits Input – if we could restrict the input coming into the method, things can become quite easier.
  4. Groups things into a Set
  5. Iterable - if utilized properly, then unnecessary if conditions and switch cases can be avoided

When to use Enumeration?

  1. As much as possible
  2. Anytime constraining input is beneficial
  3. In place of string constants
  4. 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
  1. Usage of basic Enum
  2. Using Enum as a Singleton
  3. 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

Volatile keyword, Synchronized keyword and Lock interface

Volatile Marking a member variable as volatile, makes sure, when ever the member variable is accessed, its value is always read from the...