An enum is a fixed set of named constants, and each constant can carry its own data and behaviour.
Java · intermediate · 7 min · 17 steps · free
enum Size {
SMALL(200), MEDIUM(350), LARGE(500);
final int ml;
Size(int ml) { this.ml = ml; }
int price() {
return switch (this) {
case SMALL -> 2;
case MEDIUM -> 3;
case LARGE -> 4;
};
}
}
public class EnumsDemo {
public static void main(String[] args) {
Size order = Size.MEDIUM;
int ml = order.ml;
int price = order.price();
Size fromText = Size.valueOf("LARGE");
int count = Size.values().length;
System.out.println(order + " " + ml + "ml quot; + price + " " + fromText.ordinal() + " " + count);
}
}price(). It gets its own variables on the stack.case MEDIUM -> 3.price() has finished, so its variables are gone.price.enum Size {.enum Size {.valueOf() has finished, so its variables are gone.fromText.enum Size {.MEDIUM 350ml $3 2 3.Answer: No. Enum constructors are private to the enum.
Answer: 0. Positions start at 0.
← equals and hashCode · Nested, Inner and Anonymous Classes →