Codiqo

Learn Java · lesson 43 of 61 · about 9 minutes

Interfaces and Polymorphism

Price the offers: define a contract with an interface, and treat different classes the same way through it.

What you'll learn

  • Write an interface
  • Implement it in several classes
  • Use one list for different types

The offers

Customers ask about offers: a student ticket is 20% off, and a matinee ticket is $3 off. Each offer has a name and works out a price, but each does it differently, so the desk writes an Offer interface with name() and apply(cents), plus a default describe(cents) that every offer gets for free. StudentOffer and MatineeOffer implement it. The customer types offers until done, they go into one List<Offer>, and one loop prints o.describe(priceCents) for each: Java runs each object's own apply().

Contracts

An interface lists methods a class promises to provide, without saying how:

interface Shape { double area(); String name(); }

class Circle implements Shape must provide both. Then any code that works with a Shape works with every class that implements it. That's polymorphism. A class can implement many interfaces, but extend only one class.

One list, many shapes

import java.util.List;

interface Shape {
    double area();

    default String describe() {
        return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
    }
}

class Square implements Shape {
    private final double side;
    Square(double side) { this.side = side; }
    public double area() { return side * side; }
}

class Circle implements Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    public double area() { return Math.PI * r * r; }
}

public class Main {
    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Square(3), new Circle(1));
        double total = 0;
        for (Shape s : shapes) {
            System.out.println(s.describe());
            total += s.area();
        }
        System.out.printf("Total: %.2f%n", total);
    }
}

Output

Square with area 9.00
Circle with area 3.14
Total: 12.14

Tip

Interface methods are public, so the implementing methods must be public too. A default method gives every implementation a ready-made version.

Default methods

A default method in an interface has a body, written in terms of the interface's other methods. Every class that implements the interface gets it as it is, and a class that wants something different can override it like any other method.

A greeting for everyone, and one that's different

import java.util.List;

interface Greeter {
    String name();

    default String greet() {
        return "Hello from " + name();
    }
}

class Usher implements Greeter {
    public String name() {
        return "the usher";
    }
}

class Robot implements Greeter {
    public String name() {
        return "the robot";
    }

    @Override
    public String greet() {
        return "BEEP. " + name().toUpperCase();
    }
}

public class Main {
    public static void main(String[] args) {
        for (Greeter g : List.of(new Usher(), new Robot())) {
            System.out.println(g.greet());
        }
    }
}

Output

Hello from the usher
BEEP. THE ROBOT

Now try it yourself

This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.