TExcelTAD
Home › Java › Java Interfaces

Java Interfaces

An interface is a contract: a list of methods a class promises to provide. It says what an object can do, without saying anything about how. Classes implement interfaces, and — unlike with extends — a class can implement as many interfaces as it likes.

Declaring and implementing an interface

java · try it yourself
interface Payable {
    double amountDue();          // implicitly public and abstract
}

class Invoice implements Payable {
    private final double net;
    Invoice(double net) { this.net = net; }

    @Override
    public double amountDue() {
        return net * 1.2;        // add 20% tax
    }
}

class Subscription implements Payable {
    private final int months;
    Subscription(int months) { this.months = months; }

    @Override
    public double amountDue() {
        return months * 9.99;
    }
}

class Main {
    public static void main(String[] args) {
        Payable[] bills = { new Invoice(250), new Subscription(3) };
        double total = 0;
        for (Payable p : bills) {
            System.out.printf("%s: %.2f%n", p.getClass().getSimpleName(), p.amountDue());
            total += p.amountDue();
        }
        System.out.printf("Total: %.2f%n", total);
    }
}
Invoice: 300.00
Subscription: 29.97
Total: 329.97

Interface methods are automatically public, so the implementing methods must be public too. Invoice and Subscription have nothing else in common — they don't share a parent class — yet both can be treated as Payable.

Implementing several interfaces

java · try it yourself
interface Swimmer {
    void swim();
}

interface Flyer {
    void fly();
}

class Duck implements Swimmer, Flyer {
    public void swim() { System.out.println("Duck paddles across the pond"); }
    public void fly()  { System.out.println("Duck flaps into the sky"); }
}

class Penguin implements Swimmer {
    public void swim() { System.out.println("Penguin torpedoes through the water"); }
}

class Main {
    public static void main(String[] args) {
        Swimmer[] swimmers = { new Duck(), new Penguin() };
        for (Swimmer s : swimmers) {
            s.swim();
            if (s instanceof Flyer f) {
                f.fly();
            }
        }
    }
}
Duck paddles across the pond
Duck flaps into the sky
Penguin torpedoes through the water

What an interface can contain

Member Notes
abstract methods the contract; implicitly public abstract
constants fields are implicitly public static final
default methods have a body; implementers inherit them and may override (Java 8+)
static methods helpers called on the interface name (Java 8+)
private methods helpers shared by default methods (Java 9+)

Interfaces cannot have instance fields or constructors.

Default and static methods

Default methods let an interface provide behaviour built on top of its abstract methods, and let library authors add methods to an interface without breaking existing implementations:

java · try it yourself
interface Shape {
    double PI_APPROX = 3.14;          // a constant

    double area();

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

    static Shape square(double side) {
        return new Rect(side, side);
    }
}

class Rect implements Shape {
    private final double w, h;
    Rect(double w, double h) { this.w = w; this.h = h; }
    public double area() { return w * h; }
}

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

    @Override
    public String describe() {
        return "Round thing, radius " + r;
    }
}

class Main {
    public static void main(String[] args) {
        System.out.println(new Rect(2, 3).describe());
        System.out.println(Shape.square(4).describe());
        System.out.println(new Circle(2).describe());
    }
}
Rect with area 6.0
Rect with area 16.0
Round thing, radius 2.0

Functional interfaces

An interface with exactly one abstract method is a functional interface. You can implement it with a short lambda expression instead of a whole class. The JDK's Comparator, Runnable and java.util.function types are functional interfaces:

java · try it yourself
@FunctionalInterface
interface Discount {
    double apply(double price);
}

class Main {
    static void show(String label, Discount d) {
        System.out.printf("%-12s %.2f%n", label, d.apply(80));
    }

    public static void main(String[] args) {
        show("No discount", p -> p);
        show("10% off", p -> p * 0.9);
        show("5 off", p -> Math.max(0, p - 5));
    }
}
No discount  80.00
10% off      72.00
5 off        75.00

Lambdas are explained fully in the Lambda Expressions chapter.

Interface vs. abstract class

Interface Abstract class
A class can have many one
Instance fields no yes
Constructors no yes
Method bodies default, static, private any
Describes a capability ("can be compared") a shared base ("is a vehicle")

Tip: Program to interfaces: declare variables and parameters as List, Map or your own interface types, not as concrete classes. Then you can swap implementations freely.

Test yourself

Which keyword does a class use to adopt an interface?

  1. extends
  2. implements
  3. uses
  4. inherits

How many interfaces can one class implement?

  1. Only one
  2. Two
  3. As many as needed
  4. None if it extends a class

What is a functional interface?

  1. An interface with only static methods
  2. An interface with exactly one abstract method
  3. An interface without methods
  4. Any interface with a default method