Interfaces, enums and records

Intermediate

Introduction

Inheritance shares code along one line of ancestors, but many abilities cut across class hierarchies: being priced, being comparable, being drawable. Interfaces describe such abilities as contracts. This lesson also introduces two special kinds of class that modern Java code uses everywhere: enums, for a fixed set of values, and records, for plain immutable data.

How it works

An interface lists methods a class promises to provide:

interface Priced {
    double price();
    default String label() { return String.format("%.2f", price()); }
}

A class implements it and must write every abstract method; the default method label comes for free and can use the others. A class can extend only one class but implement many interfaces, and a variable of an interface type, Priced p, can hold any object that implements it, which gives polymorphism without inheritance.

Comparable is a standard interface with one method, compareTo, returning a negative number, zero or a positive number when this object comes before, equal to or after the other. Implementing it gives objects a natural order, which Arrays.sort and Collections.sort use. Integer.compare and Double.compare write it correctly; subtracting numbers can overflow.

An enum is a type with a fixed list of constants, such as SMALL, MEDIUM and LARGE. Using an enum instead of strings or ints means a typo is a compile error. Enums can have fields, a constructor and methods, so each constant carries its own data. Size.values() lists them in order, Size.valueOf("MEDIUM") finds one by name (throwing for an unknown name), name() and ordinal() give its name and position, and enums work in switch.

A record declares data in one line: record Point(int x, int y) {}. Java generates private final fields, a constructor, accessor methods x() and y(), and equals, hashCode and toString based on the fields. Records are immutable, can implement interfaces and can have extra methods. They suit data that is just values: a coordinate, an order line, a result.

Example

// An interface with a default method, an enum with a field, and a record that implements both interfaces.
import java.util.Arrays;

interface Priced {
    double price();

    default String label() {
        return String.format("%.2f", price());
    }
}

enum Size {
    SMALL(1.0), MEDIUM(1.5), LARGE(2.0);

    private final double factor;

    Size(double factor) {
        this.factor = factor;
    }

    double factor() {
        return factor;
    }
}

record Coffee(String name, Size size) implements Priced, Comparable<Coffee> {
    public double price() {
        return 2.0 * size.factor();
    }

    public int compareTo(Coffee other) {
        return Double.compare(price(), other.price());
    }
}

public class Main {
    public static void main(String[] args) {
        Coffee[] order = { new Coffee("latte", Size.LARGE), new Coffee("espresso", Size.SMALL), new Coffee("mocha", Size.MEDIUM) };
        Arrays.sort(order); // uses compareTo
        for (Coffee c : order) System.out.println(c.name() + " " + c.size() + " " + c.label());
        System.out.println(order[0] + " " + Size.valueOf("MEDIUM").ordinal() + " " + Size.values().length);
        Priced p = order[2];
        System.out.println(p.label() + " " + (p instanceof Coffee));
    }
}
Open in compiler

Line by line

  1. Priced requires price() and supplies label() as a default method.
  2. Each Size constant carries a factor through the enum's constructor.
  3. Coffee is a record that implements Priced and Comparable, ordering coffees by price.
  4. Arrays.sort uses compareTo, so the cheapest coffee comes first.
  5. Printing a record shows its fields; valueOf and values work on the enum.

Expected result

espresso SMALL 2.00
mocha MEDIUM 3.00
latte LARGE 4.00
Coffee[name=espresso, size=SMALL] 1 3
4.00 true

In the real world

Java libraries are built on interfaces: List, Map, Runnable and Comparable are all interfaces with many implementations. Enums represent statuses, roles and settings, and records are the modern way to write data transfer objects, API responses and keys for maps.

Common mistakes

  • Comparing with subtraction in compareTo, which overflows for large values.
  • Using strings for fixed choices instead of an enum, so typos pass the compiler.
  • Calling valueOf with an unknown name, which throws IllegalArgumentException.
  • Trying to change a record's fields: they are final.

Best practices

  • Program to interfaces: declare variables as Priced or List, not the concrete class.
  • Use enums for every closed set of options.
  • Use records for plain data, and classes when an object has behaviour and changing state.

Summary

Interfaces are contracts with abstract and default methods, and a class can implement many. Comparable's compareTo gives objects a natural order for sorting. Enums define fixed sets of constants with their own fields and methods, and records generate an immutable data class from a list of fields.

Quick check

1. How many interfaces can a Java class implement?
2. What should compareTo return when this object comes first?
3. What does Size.valueOf("HUGE") do if HUGE is not a constant?
4. What does a record generate?

Key takeaways

  • An interface says what a class can do; a class extends one class but implements any number of interfaces.
  • Implement Comparable (compareTo) to let Arrays.sort and Collections.sort order your objects.
  • Enums name fixed sets of values safely; records replace boilerplate for plain data.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.