Sub topic 2
Constant-Specific Behavior
Constant-Specific Behavior
An enum constant can carry its own code. An abstract method is a method with no body. If an enum declares one, every constant must supply its own body. The result is that each constant behaves differently.
enum Operation {
PLUS {
int apply(int a, int b) { return a + b; }
},
MINUS {
int apply(int a, int b) { return a - b; }
};
abstract int apply(int a, int b);
}
public class Main {
public static void main(String[] args) {
System.out.println(Operation.PLUS.apply(2, 3)); // 5
System.out.println(Operation.MINUS.apply(2, 3)); // -1
}
}If you add a new constant and forget to give it apply, the code will not compile.
Enums That Implement Interfaces
An interface is a list of methods that a type promises to provide. An enum can implement one, just like a class.
interface Describable {
String describe();
}
enum Size implements Describable {
SMALL, LARGE;
public String describe() {
return "Size " + name().toLowerCase();
}
}
public class Main {
public static void main(String[] args) {
Describable d = Size.SMALL;
System.out.println(d.describe()); // Size small
}
}Code that expects a Describable now accepts any Size constant.
Your First Record: Data Without Boilerplate
A record is a class whose only job is to hold data. You list its components, which are the values it stores. Java then writes the constructor, the accessor methods, and equals, hashCode, and toString for you.
record Point(int x, int y) {}
public class Main {
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p.x()); // 1
System.out.println(p); // Point[x=1, y=2]
System.out.println(p.equals(new Point(1, 2))); // true
}
}The accessor is named x(), not getX().
Validating Data with Compact Constructors
A compact constructor is a constructor with no parameter list. It runs checks, and then Java assigns the fields for you.
record Range(int start, int end) {
Range {
if (start > end) {
throw new IllegalArgumentException("start must not exceed end");
}
}
}
public class Main {
public static void main(String[] args) {
System.out.println(new Range(1, 5)); // Range[start=1, end=5]
new Range(5, 1); // throws IllegalArgumentException
}
}Adding Methods and Static Factories to Records
A record can have ordinary methods. It can also have static factory methods, which are static methods that create and return an instance.
record Point(int x, int y) {
static Point origin() {
return new Point(0, 0);
}
double distanceTo(Point other) {
return Math.hypot(x - other.x, y - other.y);
}
}
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.distanceTo(Point.origin())); // 5.0
}
}Exercise
Write a record Temperature(double celsius) whose compact constructor rejects values below -273.15.
Show answer
record Temperature(double celsius) { Temperature { if (celsius < -273.15) { throw new IllegalArgumentException("below absolute zero"); } } }