Java - Declare enum type with methods inside a class

Description

Declare enum type with methods inside a class

Demo

class EnumExample {
  enum Coin {//w  ww  . ja v a2s.  c om
    PENNY(1),
    NICKEL(5),
    DIME(10),
    QUARTER(25); 

    private final int denomValue;

    Coin(int denomValue) {
      this.denomValue = denomValue;
    }

    int denomValue() {
      return denomValue;
    }

    int toDenomination(int numPennies) {
      return numPennies / denomValue;
    }
  }

  public static void main(String[] args) {
    Coin coin = Coin.NICKEL;

    System.out.println(coin.denomValue() + " cents");

    switch(coin) {
      case PENNY: System.out.println("1 cent"); break;
      case NICKEL: System.out.println("5 cent"); break;
      case DIME: System.out.println("10 cent"); break;
      case QUARTER: System.out.println("25 cent"); break;
      default: assert false;
    }

    for(int i=0; i<Coin.values().length; i++) {
      System.out.println(Coin.values()[i]);
    }
  }
}

Related Topic