Skip to content
KALANBLON
Show contents

Chapter 1 of 6 · 20 min

Interfaces and inheritance

By the end of this chapter, you'll be able to

  • Define an interface and implement it in several classes
  • Add shared behaviour with a default method
  • Factor code into an abstract class with extends and super
  • Use a lambda as the implementation of a single-method interface

One interface, several implementations

An interface is a contract: it lists methods that a class promises to provide. An abstract class goes further: it can hold fields and shared code, but you can't instantiate it directly.

interface Priced {
    double netPrice();

    default double grossPrice(double rate) {
        return Math.round(netPrice() * (1 + rate) * 100) / 100.0;
    }
}

abstract class Product implements Priced {
    private final String name;

    Product(String name) {
        this.name = name;
    }

    String name() {
        return name;
    }

    abstract String category();

    @Override
    public String toString() {
        return category() + " " + name + ": " + netPrice() + " € before tax";
    }
}

class Book extends Product {
    private final double price;

    Book(String name, double price) {
        super(name);
        this.price = price;
    }

    @Override
    public double netPrice() { return price; }

    @Override
    String category() { return "book"; }
}

class Subscription extends Product {
    private final double monthly;
    private final int months;

    Subscription(String name, double monthly, int months) {
        super(name);
        this.monthly = monthly;
        this.months = months;
    }

    @Override
    public double netPrice() { return monthly * months; }

    @Override
    String category() { return "subscription"; }
}

void main() {
    List<Product> cart = List.of(new Book("The Suns of Independence", 9.5), new Subscription("Online course", 12.0, 3));
    double total = 0;
    for (Product p : cart) {
        IO.println(p);
        total += p.grossPrice(0.2);
    }
    IO.println("Total incl. tax: " + total + " €");
    Priced delivery = () -> 4.0;
    IO.println("Delivery incl. tax: " + delivery.grossPrice(0.2) + " €");
}
book The Suns of Independence: 9.5 € before tax
subscription Online course: 36.0 € before tax
Total incl. tax: 54.6 €
Delivery incl. tax: 4.8 €
  • interface Priced declares netPrice() without defining it. Any class that writes implements Priced must provide it.
  • A default method has a body inside the interface: every implementation benefits from it. grossPrice is written once and relies on netPrice().
  • abstract class Product groups what is shared (the name, the display). abstract String category(); forces each subclass to define it.
  • class Book extends Product inherits the name and toString; super(name) calls Product's constructor.
  • Priced delivery = () -> 4.0;: an interface with only one abstract method is a functional interface, which a lambda can implement directly.
  • A class can inherit (extends) from only one class, but implement (implements) several interfaces.

36 × 1.2 = 43.2 is added to the total. The loop never tested the products' types.

Step 5 of 5
Text description of the animation
  1. The cart holds a Book and a Subscription, both seen as Product.
  2. IO.println calls toString, defined in Product, which calls category() and netPrice(): Book's versions.
  3. grossPrice, a default method of the interface, calls netPrice(): 9.5 × 1.2 = 11.4.
  4. Same line, another object: the subscription's netPrice() computes 12 × 3 = 36.
  5. 36 × 1.2 = 43.2 is added to the total. The loop never tested the products' types.

Interface or abstract class?

  • Choose an interface to describe a capability that unrelated classes can share: "has a price", "can be compared", "can be saved".
  • Choose an abstract class to share state and code between classes of the same family: all products have a name and the same display.

You often combine the two, as here: an interface for the contract, an abstract class for the shared implementation.

Your turn

Worked exercise

Solved exercise: shapes sorted by area

Write an interface Shape with a method double area() and a method default String describe() that returns the class name followed by the area rounded to two decimal places (getClass().getSimpleName() gives that name). Implement it with two records, Circle(double radius) and Rectangle(double width, double height), then display a list of shapes sorted by increasing area.

Hint 1
A record can implement an interface: record Circle(double radius) implements Shape { … }.
Hint 2
To sort a copy of the list: shapes.stream().sorted(Comparator.comparingDouble(Shape::area)).toList().
Show the solution and common mistakes
interface Shape {
    double area();

    default String describe() {
        return getClass().getSimpleName() + ": " + Math.round(area() * 100) / 100.0;
    }
}

record Circle(double radius) implements Shape {
    public double area() { return Math.PI * radius * radius; }
}

record Rectangle(double width, double height) implements Shape {
    public double area() { return width * height; }
}

void main() {
    List<Shape> shapes = List.of(new Rectangle(4, 2.5), new Circle(1.5), new Rectangle(1, 2));
    shapes.stream()
        .sorted(Comparator.comparingDouble(Shape::area))
        .forEach(s -> IO.println(s.describe()));
}
Rectangle: 2.0
Circle: 7.07
Rectangle: 10.0

In an interface, abstract methods are implicitly public: their implementation must be too (public double area()).

Common mistakes:

  • Forgetting public before area() in the record: the compiler refuses (attempting to assign weaker access privileges).
  • Sorting with Comparator.comparing(Shape::area) on double values: it works, but comparingDouble avoids turning each number into a Double object.

Summary

  1. 1An interface is a contract; implements requires providing its methods.
  2. 2A default method adds shared behaviour to every implementation.
  3. 3An abstract class shares state and code; extends inherits from it, super calls its constructor.
  4. 4An interface with a single abstract method can be implemented by a lambda.
  5. 5@Override on every overriding method catches typos.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.