Add constructor to an enum in Java
Description
The following code shows how to add constructor to an enum.
Example
//ww w . ja v a 2 s . c om
enum Apple {
A(10), B(9), C(12), D(15), E(8);
private int price; // price of each apple
Apple(int p) {
price = p;
}
int getPrice() {
return price;
}
}
public class Main {
public static void main(String args[]) {
Apple ap;
System.out.println("D costs " + Apple.D.getPrice() + " cents.\n");
System.out.println("All apple prices:");
for (Apple a : Apple.values())
System.out.println(a + " costs " + a.getPrice() + " cents.");
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »