Adding Members to an Enumeration Class : enum methods « Data Type « Java Tutorial






enum JacketSize {
  small(36), medium(40), large(42), extra_large(46), extra_extra_large(48);
  JacketSize(int chestSize) {
    this.chestSize = chestSize;
  }
  public int chestSize() {
    return chestSize;
  }
  private int chestSize;
}
class Jacket {
  public Jacket(JacketSize size) {
    this.size = size;
  }
  public String toString() {
    switch (this.size) {
    case small:
      return "S";
    case medium:
      return "M";
    case large:
      return "L";
    case extra_large:
      return "XL";
    case extra_extra_large:
      return "XXL";
    default:
      return "";
    }
  }
  private JacketSize size;
}
public class MainClass {
  public static void main(String[] args) {
    Jacket[] jackets = { new Jacket(JacketSize.medium), 
                         new Jacket(JacketSize.extra_large),
                         new Jacket(JacketSize.small), 
                         new Jacket(JacketSize.extra_extra_large) };
    System.out.println("\n\nJackets sizes available are:\n");
    for (JacketSize size : JacketSize.values()) {
      System.out.print(" " + size);
    }
    System.out.println("\n\nJackets in stock are:");
    for (Jacket jacket : jackets) {
      System.out.println(jacket);
    }
  }
}
Jackets sizes available are:
 small medium large extra_large extra_extra_large
Jackets in stock are:
M
XL
S
XXL








2.44.enum methods
2.44.1.Obtaining all ordinal values using ordinal()
2.44.2.compareTo() and equals() for enum data type
2.44.3.Using the built-in enumeration methods: values( )
2.44.4.Using valueOf()
2.44.5.Switch statement with enum
2.44.6.Adding Members to an Enumeration Class
2.44.7.Use the built-in enumeration methods.
2.44.8.Use an enum constructor, instance variable, and method.
2.44.9.Demonstrate ordinal(), compareTo(), and equals().