Enum
Enums in Java are a unique type which holds a collection of constants.Enums can be considered as a special type of java class which can hold constants as well as methods.
How to use Enum?
Enums can be used like a class.
public enum Temperature
{
HIGH,
MEDIUM,
LOW
}
- The above written enum will be saved as Temperature.java and would be compiled in the same way class is compiled.
- When compiler find the word enum it understands that this is not a class but an enum.
when later we need to access it we can access it like this:
Temperature t=Temperature.HIGH;
Let us write a small code to access the enum now
AccessEnum.java
class AccessEnum
{
public static void main(String[] args)
{
Temperature t=Temperature.HIGH;
if(t==Temperature.HIGH)
{
System.out.println("Temperature is High");
}
}
}
Enums can also hold fields as well as methods.
public enum Temperature
{
HIGH(1),// -----------> will call the constructor and pass value 1
MEDIUM(2),//-------> will call the constructor and pass value 2
LOW(3);//------------> will call the constructor and pass value 3
//A semi colon should be used to mark the end of constants.
public final int i;
Temperature(int i)
{
this.i=i;
}
}
Enums can also contain methods.
public enum Temperature
{
HIGH(1),// -----------> will call the constructor and pass value 1
MEDIUM(2),//-------> will call the constructor and pass value 2
LOW(3);//------------> will call the constructor and pass value 3
//A semi colon should be used to mark the end of constants.
public final int i;
Temperature(int i)
{
this.i=i;
}
public int getI()
{
return i;
}
}
Now let us again modify our AccessEnum.java
class AccessEnum
{
public static void main(String[] args)
{
Temperature t=Temperature.HIGH;
if(t==Temperature.HIGH)
{
System.out.println("Temperature is High");
System.out.println(t.getI());
}
}
}
Iterating through Enum
Every enum have got a static method values() which return the array of constants in enum.
for(Temperature t:Temperature.values())
{
System.out.println(t);
}
Facts about Enum
- Every enum implicitly extends java.lang.Enum.
- An enum cannot extend any other enum.
- List of constants in enum should be terminated by a semi-colon(;).
- If an enum contains constants as well as fields and methods, list of constants should come first followed by the other two.