Interfaces in Java: Complete Guide for Beginners

Think of a wall socket. The socket does not care whether you plug in a lamp, a laptop charger or a fan. It only promises a certain shape and voltage, and any device that fits can use it. A Java interface works the same way: it fixes what a class must be able to do, and leaves how to each class that plugs in.

A first interface

Say a shop wants to tell customers that their order was placed. Today it uses email, tomorrow it may use SMS. We describe the need once, as an interface:

interface Notifier {
    int MAX_LENGTH = 40;                      // constant

    void send(String message);                // must be implemented

    default void sendSafely(String message) { // ready-made helper
        if (message.length() > MAX_LENGTH) {
            message = message.substring(0, MAX_LENGTH) + "...";
        }
        send(message);
    }
}

Each way of notifying is a class that implements it:

class EmailNotifier implements Notifier {
    public void send(String message) {
        System.out.println("EMAIL -> " + message);
    }
}

class SmsNotifier implements Notifier {
    public void send(String message) {
        System.out.println("SMS   -> " + message);
    }
}

The class that needs notifications asks only for a Notifier. It never mentions email or SMS:

class OrderService {
    private final Notifier notifier;

    OrderService(Notifier notifier) {
        this.notifier = notifier;
    }

    void placeOrder(String item) {
        notifier.sendSafely("Order placed for " + item);
    }
}
OrderService the caller «interface» Notifier EmailNotifier implements SmsNotifier implements

Because OrderService only knows the contract, you can swap the implementation without touching it:

public class Main {
    public static void main(String[] args) {
        new OrderService(new EmailNotifier()).placeOrder("Wool carpet");
        new OrderService(new SmsNotifier())
                .placeOrder("Handwoven rug, 6x9 feet, free shipping");
    }
}

Expected output (put all the code above in one file named Main.java, then run javac Main.java and java Main):

EMAIL -> Order placed for Wool carpet
SMS   -> Order placed for Handwoven rug, 6x9 feet...

The second message is cut at 40 characters by the default method, which both classes inherit for free.

What you can and cannot put inside an interface

Member Rule
Normal method Has no body and is automatically public abstract. Implementing classes must declare it public.
default method Has a body. Implementing classes inherit it and may override it. Needs Java 8 or later.
static method Called as InterfaceName.method(). It is not inherited by implementing classes.
private method A helper shared by default methods. Needs Java 9 or later.
Variable Always public static final, so it is a constant and needs a value on the same line.
Constructor Not allowed, and you cannot write new Notifier(). There is no object state to set up.

One class, several contracts

A class can have only one parent class, but it can implement as many interfaces as it needs:

interface Printable { void print(); }
interface Savable   { void save(); }

class Invoice implements Printable, Savable {
    public void print() { System.out.println("Printing invoice"); }
    public void save()  { System.out.println("Saving invoice"); }
}

Calling print() and then save() on an Invoice prints Printing invoice and Saving invoice.

Why bother with interfaces?

  • Easy swapping: change email to SMS by passing a different object, without editing OrderService.
  • Easy testing: pass a fake Notifier in a unit test so no real message is sent.
  • Team work: one developer can write code against the interface while another writes the implementation.
  • Flexible design: unrelated classes can share a capability without being forced into one family tree.

Common mistakes

  • Forgetting public on the implementing method. The compiler reports that you are trying to assign weaker access.
  • Trying to change an interface variable. It is final, so Notifier.MAX_LENGTH = 50; does not compile.
  • Writing new Notifier(). Create an implementing class (or a lambda for a single-method interface) instead.

Quick recap

An interface is a promise about behaviour. Classes that implement it keep the promise in their own way, callers depend only on the promise, and one class can make many promises at once.

0 Comments