How to use Java enum as Class

Description

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.

Restrictions

Two restrictions that apply to enumerations.

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

Example 1

Enum with constructor


enum Direction {/*from  www.j ava2 s .  co  m*/
  South(10), East(9), North(12), West(8);
  private int myValue;

  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());
  }
}

The code above generates the following result.

Example 2

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


 //www .  j a va2s .c o  m
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);
    System.out.println(numQuarters);

    for (Coin c:Coin.values()) {
      System.out.println(c.denomValue());
    }

  }
}  

The code above generates the following result.





















Home »
  Java Tutorial »
    Java Data Type »




Java Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger