Core Java Fundamentals ยท Object-Oriented Programming
An interface is a promise of methods. One class can keep several promises, and be used through any of them.
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);
}
}Invoice() has finished, so its variables are gone.q is created and points to the same Invoice as inv and p. No copy is made.amountDue() has finished, so its variables are gone.label(). It gets its own variables on the stack.label() has finished, so its variables are gone.text.Invoice 100.0 -> due 110.0.