enum as Class

You can give constructors, add instance variables and methods, and implement interfaces for enum types.

When you define a constructor for an enum, the constructor is called when each enumeration constant is created.

Each enumeration constant has its own copy of any instance variables defined by the enumeration.


// Use an enum constructor, instance variable, and method. 
enum Direction {
  South(10), East(9), North(12), West(8);
  private int myValue;
  // Constructor

  Direction(int p) {
    myValue = p;
  }

  int getMyValue() {
    return myValue;
  }
}

public class Main {
  public static void main(String args[]) {

    System.out.println(Direction.East.getMyValue());

    for (Direction a : Direction.values())
      System.out.println(a + " costs " + a.getMyValue());
  }
}

Two restrictions that apply to enumerations.

  • an enumeration can't inherit another class.
  • an enum cannot be a superclass.

You can add fields, constructors, and methods to an enum. You can have the enum implement interfaces.

 
enum Coin {
  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 class Main {
  public static void main(String[] args) {
    int numPennies = 1;
    int numQuarters = Coin.QUARTER.toDenomination(numPennies);
    numPennies = Coin.QUARTER.denomValue();
    int numDimes = Coin.DIME.toDenomination(numPennies);
    numPennies = Coin.DIME.denomValue();
    int numNickels = Coin.NICKEL.toDenomination(numPennies);
    numPennies = Coin.NICKEL.denomValue();
    for (int i = 0; i < Coin.values().length; i++) {
      System.out.println(Coin.values()[i].denomValue());
    }

  }
}
  
Home 
  Java Book 
    Language Basics  

enum:
  1. enum type
  2. values( ) and valueOf( ) Methods
  3. enum as Class
  4. enum type Inherit Enum
  5. Overriding toString() to return a Token constant's value
  6. Assign a different behavior to each constant.