
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Use Enum Type with a Constructor in Java
Enum type can have a private constructor that can be used to initialize instance fields.
The EnumDemo class demonstrates this. It features a Food enum type with four constants: HAMBURGER, FRIES, HOTDOG, and ARTICHOKE. Notice that after each constant value is present in parentheses. This calls the constructor for that member to initialize the price field for that member.
We iterate over the Food values in the for loop in the main() method. In this method, we first display the name of the food constant. Next, we examine the price for that food item and display whether the price is expensive or affordable. Following this, for fun, we demonstrate the use of a switch statement with the Food enum type.
Example:
public class EnumDemo { public enum Food { HAMBURGER(7), FRIES(2), HOTDOG(3), ARTICHOKE(4); Food(int price) {this.price = price;} private final int price; public int getPrice() { return price; } } public static void main(String[] args) { for (Food f : Food.values()) { System.out.print("Food: " + f + ", "); if (f.getPrice() >= 4) { System.out.print("Expensive, "); } else { System.out.print("Affordable, "); } switch (f) { case HAMBURGER: System.out.println("Tasty"); continue; case ARTICHOKE: System.out.println("Delicious"); continue; default: System.out.println("OK"); } } } }
Output:
Food: HAMBURGER, Expensive, Tasty Food: FRIES, Affordable, OK Food: HOTDOG, Affordable, OK Food: ARTICHOKE, Expensive, Delicious
Advertisements