How do I define a field in enum type?
Category: fundamental, viewed: 699 time(s).
As we know that Java enumeration type is powerful compared to enum implementation in other programming language. Basically enum is class typed so it can have constructors, methods and fields.
In the example below you'll see how a field is defined in an enumeration type. Because each constant value for the Fruit enum is a type of Fruit itself it will have its own price field. The price field holds a unique value for each constant such as APPLE, ORANGE, etc.
In the result you'll see that the constructor will be called for each constant value and initialize it with the value passed to the constructor.
Our demo result is below:
Name: APPLE initialized. Name: ORANGE initialized. Name: MANGGO initialized. Name: GRAPE initialized. Fruit = APPLE; Price = 1.5 Fruit = ORANGE; Price = 2.0 Fruit = MANGGO; Price = 3.5 Fruit = GRAPE; Price = 5.0
Can't find what you are looking for? Join our FORUMS and ask some questions!
Download Hundreds of Complimentary Industry Resources
Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more;
all available at no cost to you. With more than 600 complimentary offers, you'll find
plenty of titles to suit your professional interests and needs.
Click Here and Sign up today!
