Core Java
core15EnumsDemo
- Path
- pkg1core/core15EnumsDemo.java
- Package
- pkg1core
- Study order
- 16
- Run
- Single-file source launch
- Command
- java pkg1core/core15EnumsDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core15EnumsDemo.java5 * --------------6 * Enums: fixed sets of constants with fields, constructors, methods, and7 * per-constant behavior. Also enums in switch.8 *9 * EXPLANATION:10 * - An enum is a type-safe set of named constants (each is a singleton).11 * - Enums can have fields, constructors, and abstract methods overridden per12 * constant (a clean alternative to switch-on-type).13 */14public class core15EnumsDemo {15 16 enum Planet {17 EARTH(5.976e24, 6.37814e6),18 MARS (6.421e23, 3.3972e6);19 20 private final double mass, radius;21 Planet(double mass, double radius) { this.mass = mass; this.radius = radius; }22 double gravity() { return 6.67300e-11 * mass / (radius * radius); }23 }24 25 // Per-constant behavior (constant-specific method bodies)26 enum Operation {27 ADD { int apply(int a, int b){ return a + b; } },28 SUB { int apply(int a, int b){ return a - b; } },29 MUL { int apply(int a, int b){ return a * b; } };30 abstract int apply(int a, int b);31 }32 33 public static void main(String[] args) {34 for (Planet p : Planet.values()) {35 System.out.printf("%s gravity = %.2f m/s^2%n", p, p.gravity());36 }37 38 for (Operation op : Operation.values()) {39 System.out.println("6 " + op + " 3 = " + op.apply(6, 3));40 }41 42 // Enum in switch + useful methods43 Planet here = Planet.EARTH;44 String note = switch (here) {45 case EARTH -> "home";46 case MARS -> "the red planet";47 };48 System.out.println(here + " is " + note + " | ordinal=" + here.ordinal() + " name=" + here.name());49 System.out.println("valueOf(\"MARS\") = " + Planet.valueOf("MARS"));50 }51}