OOP and design · Topic 11 of 12
Interface segregation
Definition​
The interface segregation principle says no class should be forced to implement methods it does not use. Prefer several small interfaces over one big one.
Example code​
A basic printer is not forced to scan
interface Printer { String print(String text); }
interface Scanner { String scan(); }
class BasicPrinter implements Printer { // only what it can really do
public String print(String text) { return "Printing: " + text; }
}
class OfficeMachine implements Printer, Scanner { // a machine that can do both
public String print(String text) { return "Printing: " + text; }
public String scan() { return "Scanned page"; }
}
class Demo {
public static void main(String[] args) {
Printer simple = new BasicPrinter();
OfficeMachine office = new OfficeMachine();
System.out.println(simple.print("report"));
System.out.println(office.print("invoice"));
System.out.println(office.scan());
}
}
// Output:
// Printing: report
// Printing: invoice
// Scanned page
Finished this page? Track your progress (saved only in your browser).