Member-only story
The enum in Java is a data type that contains a fixed set of constants
Java enums are a powerful feature introduced in JDK 5 that allows you to define a set of named constants. Here’s a deeper dive into what makes enums a versatile tool in Java.
The constructor of an enum must be private and cannot be public or protected. It must use the default access modifier.
public enum MobileOS{
ANDROID("Android"), IOS("IOS"), WINDOWS("Windows");
String os;
MobileOS (String os){
this.os=os;
}
}
In the MobileOS
enum, the constructor MobileOS(String os)
is used to initialize and store constant values for the enum constants ANDROID
, IOS
, and WINDOWS
.
Note: If the constructor were protected
or public
, it would allow the os
value to be set dynamically from outside the enum, violating the principle of enums. Enums are designed to have a fixed set of instances, and making the constructor accessible outside the enum would compromise this immutability.
Use enums when you need a fixed set of constants that represent a well-defined set of values, as illustrated in the example with MobileOS
where the enum defines a fixed set of operating systems: ANDROID
, IOS
, and WINDOWS
.
Retrieving the os
Value
public String getOs(){…