JAVA / CHAPTER 10

Interfaces and polymorphism

Advanced

Program against a contract and trace runtime method dispatch.

By the end of this chapter

  • Declare an interface contract
  • Use different implementations uniformly
  • Distinguish reference type from object type

The idea

An interface describes operations that implementing objects promise to provide. A variable with the interface type can refer to any compatible implementation. This lets a client work with a capability, such as producing a charge, without depending on the implementation details. The variable type determines which members can be requested at compile time; the actual object determines the implementation of an overridden instance method at runtime.

Use polymorphism to remove repeated type checks from client code. Each implementation can calculate its answer differently while honoring the same contract. Specify meaning as well as syntax: a method returning an int does not by itself say whether negative values are valid or which units are used.

Java example
interface Charge { int cents(); }
class FlatCharge implements Charge {
  public int cents() { return 250; }
}
class TicketCharge implements Charge {
  public int cents() { return 400; }
}
public class Main {
  public static void main(String[] args) {
    Charge[] charges = {new FlatCharge(), new TicketCharge()};
    int total = 0;
    for (Charge c : charges) total += c.cents();
    System.out.println(total);
  }
}
Result
650

The loop has one interface-based call site. Each object supplies its own cents implementation, and both results contribute to the sum.

Try it yourself

Create two LabelProvider implementations and print their labels through one interface-typed collection.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Charge c refers to a TicketCharge from the example. Which cents method executes when c.cents() is called?