Skip to content

Implementing interfaces (implements)

When a class implements an interface, it promises to provide a concrete implementation (method body) for every method declared in that interface.

Builds on Interfaces

Stage 1intro1 min read

What does implements mean?

An interface lists methods without code. When a class implements it, the class promises to write the code for every one of those methods. The compiler checks the promise: leave a method out, and the class does not compile. After that, the class can be used anywhere the interface is expected.

Simple terms

  • Interface = a named contract, such as “can take a payment.”
  • implements = “this class keeps that contract, so you can use it wherever the contract is asked for.”

Pause and predict: if CreditCard forgets pay(double amount), will the error appear when a customer pays, or while the code compiles? It appears at compile time.

A class can implement many interfaces at once, for example class MultiMachine implements Printer, Scanner, Copier. Separate the names with commas.

Example

public interface PaymentMethod {
    void pay(double amount);
}

// This class MUST have a method: void pay(double amount)
public class CreditCard implements PaymentMethod {
    private String cardNumber;

    public CreditCard(String cardNumber) {
        this.cardNumber = cardNumber;
    }

    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using card " + cardNumber);
    }
}
  • PaymentMethod says: “You must have pay(double amount).”
  • CreditCard implements PaymentMethod, so it must write pay(double amount). Here it prints the amount and the card number.
  • @Override marks the method as the one that fills the contract. If the name or parameters do not match, the compiler reports an error.
  • The constructor and the cardNumber field are normal class code. They are not part of the contract.

Where you see it in this repo

  • OCP: CreditCard, DebitCard, UPI, Paypal all implement PaymentMethod.
  • DIP: EmailService, SMSService implement NotificationChannel.
  • ISP: SimplerPrinter implements Printer; MultiPurposeMachine implements Printer, Scanner, and Copier.
  • Factory: Road, Air implement Logistics.
  • Prototype: WelcomeEmail implements EmailTemplate.

In this topic

Done with this topic?

How well do you know it?

PreviousInterfaces