Saturday, May 16, 2015

Enum

An enum type is a special data type that enables for a variable to be a set of predefined constants.
  • Enums are type-safe.
  • You can define methods or fields in an enum definition,
  • You need to define enum elements first before any other attribute in an enum class.
  • For the enum constructor; only private is permitted.
  • The compiler automatically adds some special methods when it creates an enum.
    For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. 
  • All enums implicitly extend java.lang.Enum
  • You can not create instance of enums by using new operator in Java because constructor of Enum in Java can only be private.
  • Two new collection classes EnumMap and EnumSet are added into collection package to support Java Enum.
  • Enum in Java can implement the interface.
  •  You can define abstract method and let each instance of Enum to define 
public class EnumTest {
    public enum days {
        STAURDAY,
        SUNDAY
    }
    public static void main(String[] args) {
        days day = days.SUNDAY;
        switch (day) {
        case STAURDAY:
            {
                System.out.println("day=STAURDAY");
                break;
            }
        case SUNDAY:
            {
                System.out.println("day=SUNDAY");
                break;
            }
        }
    }
}
Enum With Private Constructor:
public class EnumTest {
    public enum days {
        STAURDAY(0),
        SUNDAY(1);
        int value;
         private days(int _value){
            value = _value;
        }
    }

    public static void main(String[] args) {
        days day = days.SUNDAY;
        switch (day) {
        case STAURDAY:
            {
                System.out.println("day=STAURDAY="+day.value);
                break;
            }
        case SUNDAY:
            {
                System.out.println("day=SUNDAY="+day.value);
                break;
            }
        }
    }
} 
https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...