Lesson 17 of 20
Enums
Enums
An enum (short for enumeration) is a special class that represents a fixed set of constants. Use enums when a variable can only take one of a small set of possible values.
Basic Enum Declaration
enum Direction {
NORTH, SOUTH, EAST, WEST
}
Direction d = Direction.NORTH;
System.out.println(d); // NORTH
System.out.println(d.name()); // NORTH
System.out.println(d.ordinal()); // 0
Enum Methods
Every enum gets useful methods automatically:
name()— returns the constant name as a stringordinal()— returns the position (0-based)values()— returns an array of all constantsvalueOf(String)— converts a string to the enum constant
Enums with Fields and Constructors
Enums can have fields, constructors, and methods:
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
EARTH(5.976e+24, 6.37814e6);
private final double mass;
private final double radius;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
double surfaceGravity() {
final double G = 6.67300E-11;
return G * mass / (radius * radius);
}
}
Enums with Abstract Methods
Each constant can override an abstract method:
enum Operation {
ADD { double apply(double a, double b) { return a + b; } },
SUB { double apply(double a, double b) { return a - b; } };
abstract double apply(double a, double b);
}
Your Task
-
Create an enum
Seasonwith constantsSPRING,SUMMER,AUTUMN,WINTER, each having alabelfield (e.g. "Warm", "Hot", "Cool", "Cold") and agetLabel()method. -
Create an enum
MathOpwith constantsADD,SUB,MUL, each overriding an abstract methodint apply(int a, int b). -
In
main, iterate over all seasons printingname: label, then use eachMathOpon 10 and 3.
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.