typestar

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

  1. interface Shape demands area; records implement it.
  2. A default method gives every implementer label for free.
  3. The array of shapes dispatches to each implementation.

Keywords and builtins used here

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.

Type this snippet

Step 4 of 4 in Classes & records, step 21 of 29 in Language basics.

← Previous Next →

Interfaces in other languages