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.
package org.kodejava.basic;
enum Fruit {
APPLE(1.5f), ORANGE(2), MANGO(3.5f), GRAPE(5);
private final float price;
Fruit(float price) {
System.out.println("Name: " + this.name() + " initialized.");
this.price = price;
}
public float getPrice() {
return this.price;
}
}
public class EnumFieldDemo {
public static void main(String[] args) {
// Get the name and price of all enum constant value.
for (Fruit fruit : Fruit.values()) {
System.out.printf("Fruit = %s; Price = %5.2f%n",
fruit.name(), fruit.getPrice());
}
}
}
Our demo result is below:
Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price = 1.50
Fruit = ORANGE; Price = 2.00
Fruit = MANGO; Price = 3.50
Fruit = GRAPE; Price = 5.00
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024