Capstone: a shape hierarchy
The inheritance part ends with a hierarchy that uses everything in it: a sealed interface as the type, three records as the forms, an exhaustive switch as the only place that knows which form is which, a sorted report with a total, and a second program that checks the arithmetic against values computed by hand. The shape is the one a bookkeeping or geometry program uses for any closed set of kinds.
The model
Shape promises an id, an area and a perimeter. The three records carry the numbers their formulae need, and the triangle refuses three sides that cannot close, in the compact constructor of lesson 055.
Two of the three implement the interface methods with a public modifier, because an interface method is public and a record's own methods are not. The records have no bodies of their own beyond these methods, so their equals and toString stay generated.
The report
The table has four columns and a total row. The sort at the end uses Comparator.comparingDouble with a method reference, and the form column comes from one exhaustive switch:
import java.util.Arrays;
import java.util.Comparator;
public class Report {
public static void main(String[] args) {
Shape[] shapes = {
new Circle("c1", 2.0),
new Rect("r1", 3.0, 4.0),
new Triangle("t1", 3.0, 4.0, 5.0),
new Circle("c2", 0.5),
};
double total = 0;
double perimeter = 0;
for (Shape shape : shapes) {
total += shape.area();
perimeter += shape.perimeter();
}
System.out.printf("%-4s %-22s %7s %7s%n", "id", "form", "area", "perim");
for (Shape shape : shapes) {
System.out.printf("%-4s %-22s %7.2f %7.2f%n",
shape.id(), form(shape), shape.area(), shape.perimeter());
}
System.out.printf("%-27s %7.2f %7.2f%n", "total", total, perimeter);
Arrays.sort(shapes, Comparator.comparingDouble(Shape::area));
System.out.println("smallest " + shapes[0].id());
System.out.println("largest " + shapes[shapes.length - 1].id());
}
static String form(Shape shape) {
return switch (shape) {
case Circle(String name, double r) -> "circle r=" + r;
case Rect(String name, double w, double h) -> "rect " + w + "x" + h;
case Triangle(String name, double a, double b, double c) -> "triangle " + a + "," + b + "," + c;
};
}
}
sealed interface Shape permits Circle, Rect, Triangle {
String id();
double area();
double perimeter();
}
record Circle(String id, double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
public double perimeter() {
return 2 * Math.PI * radius;
}
}
record Rect(String id, double width, double height) implements Shape {
public double area() {
return width * height;
}
public double perimeter() {
return 2 * (width + height);
}
}
record Triangle(String id, double a, double b, double c) implements Shape {
Triangle {
if (a + b <= c || b + c <= a || a + c <= b) {
throw new IllegalArgumentException("not a triangle: " + a + " " + b + " " + c);
}
}
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public double perimeter() {
return a + b + c;
}
}
javac -Xlint:all Report.java
java Report
id form area perim
c1 circle r=2.0 12.57 12.57
r1 rect 3.0x4.0 12.00 14.00
t1 triangle 3.0,4.0,5.0 6.00 12.00
c2 circle r=0.5 0.79 3.14
total 31.35 41.71
smallest c2
largest c1
The switch pattern names the id component as well, because a record pattern must name every component in order: Circle(String name, double r) has two, since the record has two. The name is not used in the branch, which is allowed; the pattern still has to be complete.
The arithmetic checked
A report that looks plausible is not checked. The second program takes the values a person computes on paper and compares them with the methods, to a tolerance of 1e-9, and prints one line per check:
public class Checks {
public static void main(String[] args) {
check("rect 3x4 area", 12.0, new Rect(3, 4).area());
check("rect 3x4 perimeter", 14.0, new Rect(3, 4).perimeter());
check("triangle 3,4,5 area", 6.0, new Triangle(3, 4, 5).area());
check("triangle 3,4,5 perimeter", 12.0, new Triangle(3, 4, 5).perimeter());
check("circle r=1 area", Math.PI, new Circle(1).area());
try {
new Triangle(1, 1, 5);
System.out.println("bad triangle refused FAIL");
} catch (IllegalArgumentException e) {
System.out.println("bad triangle refused ok: " + e.getMessage());
}
}
static void check(String name, double expected, double actual) {
boolean ok = Math.abs(expected - actual) < 1e-9;
System.out.printf("%-28s %s %.4f%n", name, ok ? "ok" : "FAIL", actual);
}
}
sealed interface Shape permits Circle, Rect, Triangle {
double area();
double perimeter();
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
public double perimeter() {
return 2 * Math.PI * radius;
}
}
record Rect(double width, double height) implements Shape {
public double area() {
return width * height;
}
public double perimeter() {
return 2 * (width + height);
}
}
record Triangle(double a, double b, double c) implements Shape {
Triangle {
if (a + b <= c || b + c <= a || a + c <= b) {
throw new IllegalArgumentException("not a triangle: " + a + " " + b + " " + c);
}
}
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
public double perimeter() {
return a + b + c;
}
}
javac -Xlint:all Checks.java
java Checks
rect 3x4 area ok 12.0000
rect 3x4 perimeter ok 14.0000
triangle 3,4,5 area ok 6.0000
triangle 3,4,5 perimeter ok 12.0000
circle r=1 area ok 3.1416
bad triangle refused ok: not a triangle: 1.0 1.0 5.0
The triangle of sides 3, 4 and 5 has the perimeter 12 and, by Heron, the area 6: half the perimeter is 6, and 6 times 3 times 2 times 1 is 36, whose square root is 6. The refusal is the compact constructor refusing 1, 1 and 5 before area is ever called; the message carries the three values.
Counting the forms
A switch over the hierarchy can also turn a form into a label, and the labels index a pair of arrays. The count is a second use of the same exhaustive switch, which is what a closed hierarchy is for:
public class Counts {
public static void main(String[] args) {
Shape[] shapes = {
new Circle(2), new Rect(3, 4), new Triangle(3, 4, 5), new Circle(1), new Rect(1, 1),
};
String[] forms = {"circle", "rect", "triangle"};
int[] counts = new int[forms.length];
for (Shape shape : shapes) {
counts[index(form(shape))]++;
}
for (int i = 0; i < forms.length; i++) {
System.out.println(forms[i] + " " + counts[i]);
}
System.out.println("total " + shapes.length);
}
static String form(Shape shape) {
return switch (shape) {
case Circle c -> "circle";
case Rect r -> "rect";
case Triangle t -> "triangle";
};
}
static int index(String form) {
return switch (form) {
case "circle" -> 0;
case "rect" -> 1;
default -> 2;
};
}
}
sealed interface Shape permits Circle, Rect, Triangle {
double area();
}
record Circle(double radius) implements Shape {
public double area() {
return Math.PI * radius * radius;
}
}
record Rect(double width, double height) implements Shape {
public double area() {
return width * height;
}
}
record Triangle(double a, double b, double c) implements Shape {
public double area() {
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
}
javac -Xlint:all Counts.java
java Counts
circle 2
rect 2
triangle 1
total 5
Two circles, two rectangles and one triangle, and the total agrees with the five elements of the array. The index switch keeps a default because a String is open; over the sealed interface no default is possible and none is needed.
Reading the output
Check the table against the model before you trust it. The first circle has radius 2, so its area is 4 pi = 12.566 and its perimeter 4 pi = 12.566, both printed as 12.57. The rectangle is 12 by 14. The triangle is 6 by 12. The second circle has radius 0.5, so its area is 0.7854, printed 0.79, and its perimeter pi, printed 3.14.
The column totals are 12.566 + 12 + 6 + 0.785 = 31.351, printed 31.35, and 12.566 + 14 + 12 + 3.1416 = 41.708, printed 41.71. The rounded rows do not add up to the rounded total, which is normal: the total is computed from the exact values and rounded once, and a report that wants the column to add up rounds its rows and sums the rounded ones instead.
Exercises
- Add a Square(String id, double side) record and make all three programs build again.
- Add a column for the area rounded to three decimals and check the total row.
- Make Checks print one failing line by changing the expected triangle perimeter to 13 and look at the output.
- Sort the report by id instead of area and print it again.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Why is the shape hierarchy sealed?
Answer
So a switch can be exhaustive and a new form breaks every function
The closed list is what lets the compiler check that every form has a case.
-
Why must the record pattern name the id component?
Answer
A record pattern names every component in the declared order
The pattern mirrors the declaration, so a two-component record needs two patterns.
-
What do the column totals show?
Answer
The exact sum rounded once, which is why the rounded rows need not add up
Each value is rounded for display, and the total is computed from the doubles before rounding.
-
What does this program print?
public class Q1 { public static void main(String[] args) { S s = new Sq("a", 3); System.out.printf("%.2f%n", s.area()); } } sealed interface S permits Sq { double area(); } record Sq(String id, double side) implements S { public double area() { return side * side; } }Answer
9.00
The area of a square with side 3 is 9 and the format prints two decimals.
-
What does this program print?
public class Q2 { public static void main(String[] args) { System.out.println(form(new C("x", 1))); } static String form(S s) { return switch (s) { case C(String id, double r) -> "circle " + id; case R(String id, double w, double h) -> "rect " + id; }; } } sealed interface S permits C, R { } record C(String id, double r) implements S { } record R(String id, double w, double h) implements S { }Answer
circle x
The value is a C, and the pattern binds its id component to the label.
-
What does this program print?
public class Q3 { public static void main(String[] args) { try { new T(1, 1, 3); System.out.println("made"); } catch (IllegalArgumentException e) { System.out.println("refused"); } } } record T(double a, double b, double c) { T { if (a + b <= c) { throw new IllegalArgumentException("bad"); } } }Answer
refused
One plus one is not greater than three, so the compact constructor throws.
-
What does this program print?
import java.util.Arrays; public class Q4 { public static void main(String[] args) { int[] counts = new int[3]; counts[1]++; counts[1]++; counts[2]++; System.out.println(Arrays.toString(counts)); } }Answer
[0, 2, 1]
The array starts at zeros, index 1 is incremented twice and index 2 once.
-
What does this program print?
public class Q5 { public static void main(String[] args) { S[] shapes = {new C(1), new R(2, 3)}; double total = 0; for (S s : shapes) { total += s.area(); } System.out.printf("%.2f%n", total); } } sealed interface S permits C, R { double area(); } record C(double r) implements S { public double area() { return 3 * r * r; } } record R(double w, double h) implements S { public double area() { return w * h; } }Answer
9.00
The area is 3 and 6, and the loop adds both to the total.
-
Why does the total not equal the sum of the rounded rows?
Answer
The total is rounded once from the exact values
Rounding each row and rounding the exact sum can differ by a cent in the last digit.
-
What does the compact constructor of Triangle guarantee?
Answer
That no Triangle with three sides that cannot close exists
The check runs before the fields are assigned, so an impossible triangle cannot be built.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev