The Interface Segregation Principle (ISP) states that no client should be forced to depend on methods it does not use. It encourages creating small, specific interfaces rather than large, generalized ones. This principle ensures that implementing classes are not burdened with unused methods.
Consider an interface Animal
that defines multiple behaviors:
interface Animal { void eat(); void fly(); void swim(); } class Dog implements Animal { public void eat() { System.out.println("Dog eating"); } public void fly() { throw new UnsupportedOperationException("Dogs can't fly"); } public void swim() { System.out.println("Dog swimming"); } }
This violates ISP because the Dog
class is forced to implement a fly
method it cannot support.
The solution is to split the Animal
interface into smaller, more specific interfaces:
interface Eatable { void eat(); } interface Flyable { void fly(); } interface Swimmable { void swim(); } class Dog implements Eatable, Swimmable { public void eat() { System.out.println("Dog eating"); } public void swim() { System.out.println("Dog swimming"); } }
By following the Interface Segregation Principle, you ensure that classes are only responsible for implementing the methods they actually use. This results in cleaner, more focused interfaces and reduces unnecessary dependencies.