Interfaces in Java
The contract, plus behavior the contract can ship itself.
Shape[] shapes = { new Circle(1.5), new Square(2) };
for (var shape : shapes) {
System.out.printf("%.2f / %s%n", shape.area(), shape.label());
}
interface Shape {
double area();
// a default method ships behavior with the contract
default String label() { return "a " + getClass().getSimpleName(); }
}
record Circle(double radius) implements Shape {
public double area() { return Math.PI * radius * radius; }
}
record Square(double side) implements Shape {
public double area() { return side * side; }
}
How it works
interface Shapedemandsarea; records implement it.- A
defaultmethod gives every implementerlabelfor free. - The array of shapes dispatches to each implementation.
Keywords and builtins used here
CircleShapeSquareareadefaultdoubleforimplementsinterfacelabelnewpublicrecordreturnvar
The run, in numbers
- Lines
- 19
- Characters to type
- 507
- Tokens
- 129
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 91 seconds.
Step 4 of 4 in Classes & records, step 21 of 29 in Language basics.