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 abstractautomatically; defaultmethods, which have a body, and the implementing class doesn't have to override them;staticmethods, called through the interface name;privatemethods (Java 9+), for pulling out shared code inside default methods;- constants, which are
public static finalautomatically.
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.
Sign up to mark studied questions and save your progress.