×

java · level 2 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a promise to have certain methods.

A circle and a square are not related, yet both have an area. An interface lists methods without writing them: interface Shape { double area(); }. That area is an : a name, brackets and a semicolon, but no body.

A class signs the promise with , then writes every listed method, marked public. Miss one and Java refuses to compile. A class can extend only one superclass, but it can implement as many interfaces as it likes.

Now a List<Shape> can hold circles and squares. Here is a secret: List is an interface too, and ArrayList is one class that implements it.

import java.util.*;
public class Main {
    interface Shape { double area(); }
    static class Square implements Shape {
        double side;
        Square(double side) { this.side = side; }
        public double area() { return side * side; }
    }
    static class Circle implements Shape {
        double radius;
        Circle(double radius) { this.radius = radius; }
        public double area() { return 3.14 * radius * radius; }
    }
    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Square(3), new Circle(1));
        for (Shape shape : shapes) {
            System.out.println(shape.area());
        }
    }
}

Methods in an interface are public without saying so, so the class must say public too.