An interface is a promise of methods. One class can keep several promises, and be used through any of them.
Java · beginner · 8 min · 13 steps · free
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.Answer: As many as it likes. Unlike classes, interfaces can be combined.
Answer: No: it is an interface. Only classes that implement it can be created.
← Abstract Classes · Exception Handling: try, catch, finally →