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 enumconstants
. - Give each
enum
constant
a different behavior for some method. - Declare the method
abstract
in theenum
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.