Enum Size has exactly three values, written in capitals. Each one can carry data, here a price. And enums can have fields, constructors, and methods, like a class.
Main.javajava
public enum Size { SMALL(2.50), MEDIUM(3.00), LARGE(3.50); private final double price; Size(double price) { this.price = price; } public double price() { return price; }}
Size dot medium is one of the values. Values gives all of them, in order. Switch works beautifully with enums. With all three covered, no default is needed. Ordinal gives the position, and value of turns text into an enum. Run it. Medium costs three. Then each size with its position. And large costs three fifty.
Main.javajava
public class Main { public static void main(String[] args) { Size s = Size.MEDIUM; System.out.println(s + " costs " + s.price()); for (Size size : Size.values()) { String label = switch (size) { case SMALL -> "a small cup"; case MEDIUM -> "a medium cup"; case LARGE -> "a big cup"; }; System.out.println(size.ordinal() + ": " + label); } System.out.println(Size.valueOf("LARGE").price()); }}
Output
MEDIUM costs 3.0
0: a small cup
1: a medium cup
2: a big cup
3.5
Also uses Size.java
public enum Size { SMALL(2.50), MEDIUM(3.00), LARGE(3.50); private final double price; Size(double price) { this.price = price; } public double price() { return price; }}
Encapsulation hides data behind methods. Inheritance builds on a parent, with extends and super. Overriding and polymorphism let each object act in its own way. Abstract classes, and interfaces, describe what children must do. And records and enums are handy special classes.