Java Enum as Class

In this chapter you will learn:

  1. How to use enum as Class
  2. Restrictions for enum class type
  3. Example - Enum with constructor
  4. Example - Member methods

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 {/*w  w  w  .  ja  v  a  2 s .c o  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.


 //from   www  . j  a v a2s  . c om
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.

Next chapter...

What you will learn in the next chapter:

  1. enum type Inheriting Enum
  2. Ordinal value
  3. Example - Enum Ordinal value
  4. Example - Overriding toString() to return a Token constant's value
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour