Thuta Learning
Java
AdvancedProgrammingBeginner

Interfaces

JavaLesson 2335 min

What you'll walk away with

  • Declare an interface and implement it with implements and public methods
  • Program against an interface type instead of a concrete class so implementations can be swapped
  • Extend an interface safely with default methods and resolve a default-method conflict
  • Implement several interfaces at once and switch over a sealed interface

Explain it simply

Interfaces in plain language

An interface is a contract describing what a class must be able to do. It declares method names, parameters and return types, but says nothing about how the work is done. When a class declares implements Notifier, it promises to write every method in the contract, and the compiler refuses it if it does not.

Think of a wall socket. The socket defines only a shape and a voltage. A kettle, a phone charger or a lamp can plug in as long as the plug fits. The wiring in the wall never needs to know which appliance is attached, and code that uses an interface never needs to know which class sits behind it.

Problem → Why → Solution

The problem: welded to one concrete class

An order service uses an EmailSender class directly, as a field, to email the customer after every order. When the business also wants SMS, OrderService itself has to change, and every unit test run sends real emails. OrderService only needs to know that the customer must be notified; which channel delivers the message is not its job.

OrderService.java
class OrderService {
  private final EmailSender email = new EmailSender();   // welded to one class

  void placeOrder(String customer) {
    // ... save the order ...
    email.sendEmail(customer, "Order confirmed");   // SMS? push? tests?
  }
}

Depend on a capability, not a class

The trouble is that OrderService knows one specific class, EmailSender. Create a Notifier interface and let OrderService accept only the Notifier type, and you can hand it email, SMS, push or a fake notifier for tests through its constructor. Not one line of OrderService has to change.

Core concept: an interface is a capability contract

In interface Notifier { void send(String message); }, methods without a body are implicitly public and abstract. So an implementing class must write them as public; leave public off and you get the compile error "attempting to assign weaker access privileges; was public". Any field you declare in an interface is implicitly a public static final constant, so an interface cannot hold instance state.

A class can extend only one superclass, but it can implement as many interfaces as it likes: class SmartSpeaker implements Playable, Rechargeable. An interface is also a type: a Notifier variable, a List<Notifier> or a Notifier parameter accepts an object of any implementing class. Writing code against the interface type is called programming to an interface, and it lets you swap implementations later.

Since Java 8, interfaces can contain default methods and static methods with bodies, and since Java 9 private helper methods as well. The main purpose of default methods is evolving an interface without breaking it: adding an abstract method to an interface with hundreds of implementing classes breaks every one of them, while adding a default method gives them all the new behaviour with no edits.

Interface memberWhat it means
void send(String m);public abstract; every implementer must write it
default void x() { ... }has a body; implementers may override it (Java 8+)
static Notifier none() { ... }a helper called on the interface name (Java 8+)
private String clean(String m) { ... }a helper shared by default methods (Java 9+)
int MAX = 160;a public static final constant

An interface with exactly one abstract method is a functional interface and can be implemented briefly with a lambda (the Lambdas lesson covers this). Since Java 17, a sealed interface can close the list of types allowed to implement it, so, as the deeper section shows, the compiler can check that a switch handles every case.

The interface is the plug shape, classes are appliances
  1. Interface declares method signatures
  2. Class implements them as public methods
  3. Client holds only the interface type
  4. The plugged-in class does the work

The smaller the interface, the more appliances fit the plug; an interface with ten methods is hard to implement.

General pattern

java
interface Capability {
  ReturnType action(Params p);                  // implicitly public abstract
  default ReturnType extra() { ... action(...) ... }   // optional body
}

class Implementation implements Capability, OtherCapability {
  @Override
  public ReturnType action(Params p) { ... }    // must be public
}

Capability c = new Implementation();            // program to the interface

The interface declares the required methods, and default methods build on them. A class implements one or more interfaces and writes the methods as public.

Worked example: notification channels

The Notifier interface has one abstract method, send(), and one default method, sendUrgent(), built on top of send(). EmailNotifier and SmsNotifier write only send() and get sendUrgent() for free. When main loops over a List<Notifier>, each channel delivers the message its own way.

Main.java
import java.util.List;

public class Main {
  public static void main(String[] args) {
    Notifier notifier = new EmailNotifier();
    notifier.send("Welcome to Java!");

    List<Notifier> channels = List.of(new EmailNotifier(), new SmsNotifier());
    for (Notifier channel : channels) {
      channel.send("Your order has shipped");
    }

    new SmsNotifier().sendUrgent("Server is down");
  }
}

interface Notifier {
  void send(String message);

  default void sendUrgent(String message) {
    send("URGENT: " + message);
  }
}

class EmailNotifier implements Notifier {
  @Override
  public void send(String message) {
    System.out.println("Email sent: " + message);
  }
}

class SmsNotifier implements Notifier {
  @Override
  public void send(String message) {
    System.out.println("SMS sent: " + message);
  }
}

Code breakdown

  1. The contractvoid send(String message);

    With no body it is implicitly public abstract; every class that implements Notifier must write it.

  2. Default methoddefault void sendUrgent(String message) {

    A method with a body, inside the interface. It calls send(), so at runtime the object's own send() runs, which is why the urgent message comes out through SMS.

  3. Implementing classclass SmsNotifier implements Notifier {

    implements makes SmsNotifier a Notifier. Its send() must be public; remove public and you get the weaker access privileges error.

  4. Program to the interfaceList<Notifier> channels = List.of(new EmailNotifier(), new SmsNotifier());

    The list's element type is the interface, so any Notifier implementation fits. Adding a PushNotifier later requires no change to the loop.

You should see
Email sent: Welcome to Java!
Email sent: Your order has shipped
SMS sent: Your order has shipped
SMS sent: URGENT: Server is down

Several interfaces and a default conflict

SmartSpeaker implements both Playable and Rechargeable. Both interfaces supply a describe() default, so Java cannot choose one, and unless SmartSpeaker overrides describe() you get the compile error "class SmartSpeaker inherits unrelated defaults for describe()". Inside the override, InterfaceName.super.method() picks which version to call.

Devices.java
public class Devices {
  public static void main(String[] args) {
    SmartSpeaker speaker = new SmartSpeaker();
    speaker.play("jazz");
    speaker.charge();
    System.out.println(speaker.describe());
  }
}

interface Playable {
  void play(String track);
  default String describe() { return "plays audio"; }
}

interface Rechargeable {
  void charge();
  default String describe() { return "has a battery"; }
}

class SmartSpeaker implements Playable, Rechargeable {
  @Override
  public void play(String track) { System.out.println("Playing " + track); }

  @Override
  public void charge() { System.out.println("Charging..."); }

  @Override
  public String describe() {   // required: both interfaces provide describe()
    return Playable.super.describe() + " and " + Rechargeable.super.describe();
  }
}

The output is Playing jazz, then Charging..., then plays audio and has a battery.

Sealed interfaces, records and record patterns

Suppose a payment result can only be Approved or Declined. A sealed interface closes that list and records carry the data. Java 21's record patterns, such as case Approved(String ref), check the type and pull out the fields in one step. Forget to handle Declined and the switch does not compile.

Results.java
import java.util.List;

public class Results {
  public static void main(String[] args) {
    List<PaymentResult> results =
        List.of(new Approved("TX-42"), new Declined("card expired"));
    for (PaymentResult result : results) {
      System.out.println(message(result));
    }
  }

  static String message(PaymentResult result) {
    return switch (result) {
      case Approved(String reference) -> "Paid, reference " + reference;
      case Declined(String reason) -> "Declined: " + reason;
    };
  }
}

sealed interface PaymentResult permits Approved, Declined {}

record Approved(String reference) implements PaymentResult {}

record Declined(String reason) implements PaymentResult {}

In real projects

Interfaces in real projects

The whole Java ecosystem is built on interfaces. In the collections framework, List, Map and Set are interfaces and ArrayList and HashMap are implementations. Comparable and Comparator are interfaces too, so making your own class sortable means implementing compareTo(). JDBC's Connection and ResultSet are interfaces as well, implemented by each database vendor's driver.

  • Repository pattern: behind a UserRepository interface sits a database implementation in production and an in-memory one in tests, so service code can be tested without a database.
  • Dependency injection: frameworks such as Spring look at a constructor parameter's interface type and supply a suitable implementation.
  • Plugins: payment gateways, storage providers and AI model providers sit behind one interface and are chosen by configuration; a new provider is just a new class.

Common mistakes

Common mistakes with interfaces

Forgetting public on the implementing method

class Email implements Notifier { void send(String m) { ... } } fails with "send(String) in Email cannot implement send(String) in Notifier; attempting to assign weaker access privileges; was public". Interface methods are always public, so the implementing method must be public too.

One huge interface for everything

Put send(), sendBulk(), scheduleCampaign() and exportReport() into Notifier, and even a simple SMS class must write four methods it does not need, usually by throwing UnsupportedOperationException. Keep interfaces small and focused; a class can implement as many as it needs.

Adding an abstract method to a published interface

Add an abstract method to an interface that five teams implement, and every one of their implementations stops compiling. If the new method can be expressed with existing ones, add it as a default method so everything keeps working and only the classes that care override it.

Leaving a default-method conflict unresolved

When two interfaces provide default methods with the same signature, the class fails with "inherits unrelated defaults". Override the method in the class and decide explicitly, with syntax such as A.super.describe(), which version to use or how to combine both.

Mini challenge

Mini challenge: a repository interface and a service

Write a UserRepository interface for storing users, an InMemoryUserRepository implementation backed by a LinkedHashMap, and a RegistrationService that refuses to register a duplicate ID. The service must know only the interface type, so a database implementation can replace the in-memory one later.

  • UserRepository has save(User), findById(int) returning Optional<User>, and findAll()
  • InMemoryUserRepository writes every method as public with @Override
  • RegistrationService receives a UserRepository through its constructor
  • Registering a duplicate ID returns "id <n> is taken" and saves nothing
Users.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class Users {
  public static void main(String[] args) {
    UserRepository repo = new InMemoryUserRepository();
    RegistrationService service = new RegistrationService(repo);
    // TODO: register (1, "Aye"), (2, "Bo"), then (1, "Copycat") and print each result
    // TODO: print repo.findById(2), repo.findById(9) and repo.findAll()
  }
}

record User(int id, String name) {}

interface UserRepository {
  // TODO: save, findById, findAll
}

class InMemoryUserRepository implements UserRepository {
  private final Map<Integer, User> users = new LinkedHashMap<>();
  // TODO: implement the three methods
}

class RegistrationService {
  // TODO: hold a UserRepository and write String register(int id, String name)
}

Expected: Six lines: registered Aye, registered Bo, id 1 is taken, Optional[User[id=2, name=Bo]], Optional.empty and [User[id=1, name=Aye], User[id=2, name=Bo]].

Show hint

Optional.ofNullable(users.get(id)) returns Optional.empty when the ID is missing. Returning List.copyOf(users.values()) from findAll() stops callers editing the map. In register(), check for a duplicate with findById(id).isPresent().

Show solution
Users.java
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class Users {
  public static void main(String[] args) {
    UserRepository repo = new InMemoryUserRepository();
    RegistrationService service = new RegistrationService(repo);
    System.out.println(service.register(1, "Aye"));
    System.out.println(service.register(2, "Bo"));
    System.out.println(service.register(1, "Copycat"));
    System.out.println(repo.findById(2));
    System.out.println(repo.findById(9));
    System.out.println(repo.findAll());
  }
}

record User(int id, String name) {}

interface UserRepository {
  void save(User user);

  Optional<User> findById(int id);

  List<User> findAll();
}

class InMemoryUserRepository implements UserRepository {
  private final Map<Integer, User> users = new LinkedHashMap<>();

  @Override
  public void save(User user) {
    users.put(user.id(), user);
  }

  @Override
  public Optional<User> findById(int id) {
    return Optional.ofNullable(users.get(id));
  }

  @Override
  public List<User> findAll() {
    return List.copyOf(users.values());
  }
}

class RegistrationService {
  private final UserRepository repository;

  RegistrationService(UserRepository repository) {
    this.repository = repository;
  }

  String register(int id, String name) {
    if (repository.findById(id).isPresent()) {
      return "id " + id + " is taken";
    }
    repository.save(new User(id, name));
    return "registered " + name;
  }
}

Quick quiz 1 / 3

Given interface Greeter { String name(); default String greet() { return "Hello, " + name(); } } and class Bot implements Greeter { public String name() { return "Bot"; } }, what does new Bot().greet() return?

Quick quiz 2 / 3

What happens with class Email implements Notifier { void send(String m) { } }, where Notifier declares void send(String m);?

Quick quiz 3 / 3

Which statement about a Java class is true?

What to remember

  • An interface is a capability contract of method signatures, and implementing methods must be public.
  • A class extends one superclass but can implement many interfaces.
  • Code written against an interface type can swap implementations easily, including fakes in tests.
  • Default methods evolve an interface without breaking implementers, and a sealed interface closes the list of implementers.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Interfaces | Thuta Learning