If we want to represent a Group Named Constants then we should go for enum
Example of Enum
enum Month{
JAN,FEB,MAR;
}
- Semicolon (;) is optional
- enum concept was introduced in 1.5 Version
- The main objective of enum is to Define our own Data Types(Enumerated Data Types)
- When compared with other languages enum, java enum is more powerful
Internally Implementation of enum :
- Every enum Internally implemented by using Class Concept.
- Every enum Constant is Always public static final.
- Every enum Constant Represents an Object of the Type enum.
Example of enum :
enum Month{
JAN,FEB,MAR;
}
Internal Implementation of enum
class Month{
public static final Month JAN = new Month();
public static final Month FEB = new Month();
public static final Month MAR = new Month();
}
A Tree structure using enum
package com.enumTest; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; public class Demo { enum Month{ JAN(1,"january",Climate.WINTER),FEB(2,"Februrary",Climate.WINTER),MAR(3,"March",Climate.SUMMER),APR(4,"April",Climate.SUMMER), MAY(5,"May",Climate.SUMMER),JUN(6,"June",Climate.RAINY),JUL(7,"July",Climate.RAINY),AUG(8,"August",Climate.RAINY),SEP(9,"September",Climate.RAINY), OCT(10,"October",Climate.WINTER),NOV(11,"November",Climate.WINTER),DEC(12,"December",Climate.WINTER); int width; String name; Climate climate; Month(int width,String name, Climate climate ){ this.width=width; this.name=name; this.climate=climate; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Climate getClimate() { return climate; } enum Climate{ SUMMER,WINTER,RAINY; int totalWidth; public int getTotalWidth() { return totalWidth; } enum Decade{ Decade; } } } public static void main(String[] args) { int grandTotal; List<Month> temp = new ArrayList<>(); temp.add(Month.JAN); temp.add(Month.FEB); temp.add(Month.MAR); temp.add(Month.APR); temp.forEach(month -> month.climate.totalWidth=month.climate.totalWidth+month.width); EnumSet.allOf(Month.Climate.class).forEach(climate -> System.out.println(climate.totalWidth)); grandTotal = temp.stream().mapToInt(Month::getWidth).sum(); } }