You will always have the joy of using enums, but have you ever thought that enums demonstrate the common characteristics of Object Oriented Design? I.e inheritance and abstraction. So what stops you from creating your own enum construct with the available constructs, i.e classes. I was just playing around with them and could build one.
Let's first get to know the characteristics of an enum.
Characterics of an enum
- Enums cannot be instantiated with the 'new' keyword since the constructor is private.
- Enums can contain only a finite set of states. i.e the value/s an Enum can contain should have been defined already.
- Enums do behave as regular classes complying with the OOD features like inheritance, polymorphism, encapuslation and abstraction
- The only exception I have noticed is that it does not allow generics, at least in Java 8.
- Abstract class has been used as the main construct for the LocaleEnum reference- this will prevent instantiation and at the same time allow us to define abstract methods inside it.
- Handles to get the Enum states (values) have been represented by public static methods.
- Each Enum state has been implemented as a static nested inner class which also inherits from the main enum class-
As evident, the LocaleEnum cannot be instantiated but assigned with a preset value. Also, the enum methods can be called just like of any other regular class.
Further, class-level or method level type parameters can be used with freedom, giving a more flexibility. Below image shows an example of a class level type parameter being used.
Comments
Post a Comment