- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do we use an enum type with a constructor in Java?n
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
- Related Articles
- How do we use an enum type with a constructor in Java?
- How do we use enum keyword to define a variable type in C#?
- Why do we need a copy constructor and when should we use a copy constructor in Java?
- Enum constructor in Java
- How to call another enum value in an enum's constructor using java?
- How to use an enum with switch case in Java?
- Can we create an enum with custom values in java?
- Can we extend an enum in Java?
- Can we define an enum inside a class in Java?
- Can we define an enum inside a method in Java?
- What is a Type-safe Enum in Java?
- Can you use a switch statement around an enum in Java?
- What is MySQL ENUM data type? What are the advantages to use ENUM data type?
- How to define an enumerated type (enum) in C++?
- Can we define constructor inside an interface in java?
- How can we create and use ENUM columns in MySQL?

Advertisements