Video in progress

What is an interface and how does a class use it?

An interface is a contract a class must fulfill: a set of method signatures. A class adopts an interface through implements and must implement all of its abstract methods. A single class can implement several interfaces.

📖 Answer

public interface Discount {
    long apply(long price);
}

public class PercentDiscount implements Discount {
    private final int percent;
    public PercentDiscount(int percent) { this.percent = percent; }

    @Override
    public long apply(long price) {
        return price - price * percent / 100;
    }
}

What an interface can contain (Java 17/21):

  • abstract methods, which are public abstract automatically;
  • default methods, which have a body, and the implementing class doesn't have to override them;
  • static methods, called through the interface name;
  • private methods (Java 9+), for pulling out shared code inside default methods;
  • constants, which are public static final automatically.

It can't have instance fields or a constructor.

In practice you declare the variable with the interface type: Discount d = new PercentDiscount(10);. The code depends on the contract, not on a concrete class, so swapping the implementation is easy.