Careeroza
Enums with Fields and Methods
Constructors, Fields and Methods
Example
Each constant calls the private constructor with its own values.
public class Main {
public static void main(String[] args) {
for (Plan p : Plan.values()) {
System.out.printf("%-8s Rs %4d/month, %2d screens, yearly Rs %d%n",
p, p.getMonthlyPrice(), p.getScreens(), p.yearlyPrice());
}
System.out.println(Plan.fromLabel("premium"));
}
}
enum Plan {
MOBILE(149, 1),
BASIC(199, 1),
STANDARD(499, 2),
PREMIUM(649, 4);
private final int monthlyPrice;
private final int screens;
Plan(int monthlyPrice, int screens) { // enum constructors are always private
this.monthlyPrice = monthlyPrice;
this.screens = screens;
}
int getMonthlyPrice() { return monthlyPrice; }
int getScreens() { return screens; }
int yearlyPrice() {
return monthlyPrice * 12 * 85 / 100; // 15% yearly discount
}
static Plan fromLabel(String label) {
return Plan.valueOf(label.trim().toUpperCase());
}
}Output
MOBILE Rs 149/month, 1 screens, yearly Rs 1519 BASIC Rs 199/month, 1 screens, yearly Rs 2029 STANDARD Rs 499/month, 2 screens, yearly Rs 5089 PREMIUM Rs 649/month, 4 screens, yearly Rs 6619 PREMIUM
Constant-Specific Behaviour
Example
Each constant can override an abstract method. This replaces long if/else chains.
public class Main {
public static void main(String[] args) {
for (Operation op : Operation.values()) {
System.out.println("12 " + op.symbol + " 4 = " + op.apply(12, 4));
}
}
}
enum Operation {
ADD("+") { int apply(int a, int b) { return a + b; } },
SUBTRACT("-") { int apply(int a, int b) { return a - b; } },
MULTIPLY("*") { int apply(int a, int b) { return a * b; } },
DIVIDE("/") { int apply(int a, int b) { return a / b; } };
final String symbol;
Operation(String symbol) { this.symbol = symbol; }
abstract int apply(int a, int b);
}Output
12 + 4 = 16 12 - 4 = 8 12 * 4 = 48 12 / 4 = 3