enum in Java
Last Updated :
23 Aug, 2023
In Java, Enumerations or Java Enum serve the purpose of representing a group of named constants in a programming language. Java Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command-line flags, etc. The set of constants in an enum type doesn’t need to stay fixed for all time.
What is Enumeration or Enum in Java?
A Java enumeration is a class type. Although we don’t need to instantiate an enum using new, it has the same capabilities as other classes. This fact makes Java enumeration a very powerful tool. Just like classes, you can give them constructors, add instance variables and methods, and even implement interfaces.
Enum Example:
The 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.).
One thing to keep in mind is that, unlike classes, enumerations neither inherit other classes nor can get extended(i.e become superclass). We can also add variables, methods, and constructors to it. The main objective of an 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.
1. Declaration outside the class
Java
enum Color {
RED,
GREEN,
BLUE;
}
public class Test {
public static void main(String[] args)
{
Color c1 = Color.RED;
System.out.println(c1);
}
}
|