Skip to content

Interfaces

An interface is a contract. It lists method names and parameters, and implementing classes write the code. Newer Java also allows a few methods with a body.

Stage 1intro1 min read

What is an interface?

Sometimes your code needs “something that can send a message,” whether email or SMS. An interface lets you say that.

An interface is a contract. It lists what a class must be able to do, such as send(String message). It does not say how. Classes that implement (agree to follow) it write the code.

It is like a job description: “Anyone hired for this role must be able to do X and Y.” The interface says what callers may ask for. Each class decides how.

Newer Java also allows default, static and private methods with a body, but the main job is still to list what.

Why use it?

  • So you can program to the contract, not to one class. Your code asks for “something that can send,” not for EmailService.
  • So you can swap implementations without changing other code, for example email to SMS.

Simple example

// Contract: "Anyone who implements this must have a send method."
public interface NotificationChannel {
    void send(String message);
}

// One implementation
public class EmailService implements NotificationChannel {
    @Override
    public void send(String message) {
        System.out.println("Email: " + message);
    }
}

// Another implementation
public class SMSService implements NotificationChannel {
    @Override
    public void send(String message) {
        System.out.println("SMS: " + message);
    }
}
  • send in NotificationChannel ends with ; and has no { ... } body. That is the contract.
  • EmailService and SMSService both “sign” it with implements NotificationChannel and write their own send body.
  • @Override tells the compiler: “this fulfils a method from the contract.” If it does not match, the code will not compile.
  • A caller can hold either object as a NotificationChannel and call send("Hi"). It prints Email: Hi or SMS: Hi.

Where you see it in this repo

  • SOLID DIP (depend on the contract): NotificationChannel in Principles/SOLID/DIP/GoodCode. (ConceptsDemo.java calls it Notifier.) NotificationService uses the interface, not Email or SMS.
  • SOLID OCP (add types without editing old code): PaymentMethod. Many payment types implement pay(amount).
  • Factory pattern: Logistics. Road and Air implement it.
  • Prototype: EmailTemplate is the contract for clone, setContent and send.

In this topic

Done with this topic?

How well do you know it?

PreviousCoupling and Cohesion