Core Java Fundamentals ยท Object-Oriented Programming

Interfaces

An interface is a promise of methods. One class can keep several promises, and be used through any of them.

InterfacesDemo.java

interface Payable {
    double amountDue();
}

interface Printable {
    String label();
}

class Invoice implements Payable, Printable {
    double total;
    Invoice(double total) { this.total = total; }

    public double amountDue() { return total + total / 10; }
    public String label() { return "Invoice " + total; }
}

public class InterfacesDemo {
    public static void main(String[] args) {
        Invoice inv = new Invoice(100);
        Payable p = inv;
        Printable q = inv;
        double due = p.amountDue();
        String text = q.label();
        System.out.println(text + " -> due " + due);
    }
}

Step by step

  1. An Invoice keeps both promises: Payable and Printable.
  2. Invoice() has finished, so its variables are gone.
  3. An Invoice keeps both promises: Payable and Printable.
  4. The same object, seen through the Payable interface.
  5. q is created and points to the same Invoice as inv and p. No copy is made.
  6. Calls Invoice's amountDue: 100 + 10 = 110.
  7. amountDue() has finished, so its variables are gone.
  8. Calls Invoice's amountDue: 100 + 10 = 110.
  9. Java calls label(). It gets its own variables on the stack.
  10. label() has finished, so its variables are gone.
  11. The value it returned, "Invoice 100.0", is stored in text.
  12. It prints Invoice 100.0 -> due 110.0.
  13. One object, two interface views. Code that only needs to "pay" can accept any Payable.