Intermediate 30 min read

Interfaces

By the end of this lesson, you'll be able to:

  • Define an interface as a pure contract with no implementation at all
  • Implement an interface in a class using implements
  • Explain the difference between an interface and an abstract class

Prerequisites: "Abstract Classes"

A contract with no body at all

public interface Payable {
    Decimal calculatePayment();
}

public class Contractor implements Payable {
    public Decimal hourlyRate;
    public Integer hoursWorked;

    public Decimal calculatePayment() {
        return hourlyRate * hoursWorked;
    }
}

An interface can't have any method bodies, fields, or constructors — it's purely a promise: "any class that implements Payable guarantees it has a calculatePayment() method." How each class fulfils that promise is entirely up to it.

One class, several unrelated interfaces

public interface Payable {
    Decimal calculatePayment();
}

public interface Schedulable_Custom {
    String getSchedule();
}

public class Contractor implements Payable, Schedulable_Custom {
    public Decimal calculatePayment() { return 5000; }
    public String getSchedule() { return 'Mon-Fri, 9-5'; }
}

Unlike extends (a class can only extend one parent), a class can implements multiple interfaces at once — interfaces describe unrelated capabilities a class can mix and match, not a single "is-a" lineage.

Interface vs abstract class

An abstract class can mix real, shared implementation with abstract methods still to be filled in, and a class can only extend one of them. An interface has zero implementation at all, and a class can implement many of them together. Reach for an interface when you're describing an unrelated capability ("this can be paid," "this can be scheduled") rather than a shared lineage.

Exercise

Write an interface Printable with a method String toPrintFormat(). Implement it in a class Invoice that returns "Invoice #" plus an invoiceNumber field.

Show hint

public interface Printable { String toPrintFormat(); }

APEX

Interfaces Quiz

1. How many interfaces can a single class implement?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

An interface is a pure contract — a list of method signatures with zero implementation — that any class can promise to fulfil using implements, regardless of what it inherits from.