Enum

Each Enum Instance a different sub-class

In this example we shall show you how to have each enum instance represent a different sub-class. To make each enum instance represent a different sub-class one should perform the following steps:

  • Create an enum with different enum constants.
  • Give each enum constant a different behavior for some method.
  • Declare the method abstract in the enum type and override it with a concrete method in each constant. Such methods are known as constant-specific methods,

as described in the code snippet below.  
 

// from http://download.oracle.com/javase/1,5.0/docs/guide/language/enums.html
public enum Operation {
  PLUS   { double eval(double x, double y) { return x + y; } },
  MINUS  { double eval(double x, double y) { return x - y; } },
  TIMES  { double eval(double x, double y) { return x * y; } },
  DIVIDE { double eval(double x, double y) { return x / y; } };
 
  // Do arithmetic op represented by this constant
  abstract double eval(double x, double y);
}

Related Article:

Reference: Java Secret: Using an enum to build a State machine from our JCG partner Peter Lawrey at the Vanilla Java
  
This was an example of how to have each enum instance represent a different sub-class in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button