Home » Java Basics » data types » Enum » Each Enum Instance a different sub-class

About Ilias Tsagklis

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

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments