enum in Java
Enums are used when we know all possible values at compile time, such as choices on a menu.
In Java (from 1.5), enums are represented using enum data type.
In Java, we can also add variables, methods and constructors to it.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.
Output :
RED
// enum declaration inside a class. public class Test { enum Color { RED, GREEN, BLUE; } // Driver method public static void main(String[] args) { Color c1 = Color.RED; System.out.println(c1); } }
First line inside enum should be list of constants and then other things like methods, variables and constructor.
Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can’t create child enums.
We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.
// A Java program to demonstrate that we can have
// main() inside enum class.
enum Color
{
RED, GREEN, BLUE;
// Driver method
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
Output :
RED
Enum and Inheritance :
- All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
- toString() method is overridden in java.lang.Enum class,which returns enum constant name.
- enum can implement many interfaces.
enum and constructor :
- enum can contain constructor and it is executed separately for each enum constant at the time of enum class loading.
- We can’t create enum objects explicitly and hence we can’t invoke enum constructor directly.
enum and methods :
- enum can contain concrete methods only i.e. no any abstract method.
Output:
Constructor called for : RED Constructor called for : GREEN Constructor called for : BLUE RED Universal Color
Enum with Customized Value in Java
By default enums have their own string values, we can also assign some custom values to enums.
- We have to create parameterized constructor for this enum class. Why? Because as we know that enum class’s object can’t be create explicitly so for initializing we use parameterized constructor. And the constructor cannot be the public or protected it must have private or default modifiers. Why? if we create public or protected, it will allow initializing more than one objects. This is totally against enum concept.
- We have to create one getter method to get the value of enums.
Output:
name : RED action: STOP name : GREEN action: GO name : ORANGE action: SLOW DOWN
No comments:
Post a Comment
Note: only a member of this blog may post a comment.