Enumeration

Aim

  • Provide Options

Enum vs Class

  • Type Safety

public static final int SIZE_SMALL  = 1;
public static final int SIZE_MEDIUM = 2;
public static final int SIZE_LARGE  = 3;

public void setSize(int newSize) { ... }

obj.setSize(15); // Compiles but likely to fail later
public enum Size { SMALL, MEDIUM, LARGE };

public void setSize(Size s) { ... }

obj.setSize( ? ); // Can't even express the above example with an enum
  • Able to use switch

  • Can be extended

  • Can be Override

Method

  • ValueOf

  • Ordinal

  • CompareTo

  • toString and name (convert enum into string type)

Last updated

Was this helpful?