Clients should not be obligated to rely on interfaces they don’t utilize.
Example: Consider an interface that imposes irrelevant methods on implementing classes.
// Violation of ISP
public interface Worker {
void work();
void eat();
}
public class HumanWorker implements Worker {
public void work() {
System.out.println("Human working");
}
public void eat() {
System.out.println("Human eating");
}
}
public class RobotWorker implements Worker {
public void work() {
System.out.println("Robot working");
}
public void eat() {
// Robots don't eat
}
}
// Following ISP
public interface Workable {
void work();
}
public interface Eatable {
void eat();
}
public class HumanWorker implements Workable, Eatable {
public void work() {
System.out.println("Human working");
}
public void eat() {
System.out.println("Human eating");
}
}
public class RobotWorker implements Workable {
public void work() {
System.out.println("Robot working");
}
}
In this scenario, RobotWorker need not implement eat(), thereby adhering to the ISP.
Previous: Liskov Substitution Principle (LSP)

Leave a Reply