The Interface Segregation Principle states the following: Clients of a class should not be forced to depend on those of its methods they don't use. Suppose you are building an animal simulator and you design an interface as shown below. In the beginning, you think that the application will accept only animals. So you design the IBehaviour interface to have three methods. eat(), sleep(), move(). Now let's assume that the application would not simulate animals, it would also simulate plants. The solution sounds quite simple, you just create the Plant class and implement the IBehaviour interface. But there is a problem a plant can't move and also can't sleep, so the methods sleep() and move() would end up having nothing inside as shown below. @Override public void move() { throw new UnsupportedOperationException("Not supported"); } @Override public void sleep() { throw new ...
Liskov Substitution Principle can be stated as: A type must be substitutable by its subtypes without altering the correctness of the application. To make it easier let's start with an example. See the image below: As you can see there is an interface IAnimal that defines two methods, speak() and sleep(). The IAnimal interface is implemented by two classes Parrot and Elephant. So far, so good but let's say that we should include ants in the application. To incorporate this change create an additional class called Ant that implements IAnimal. Since ants do not speak once you implement the interface the code would look something like this: @Override public void speak() { throw new UnsupportedOperationException("Not supported yet."); } Now we can see a problem that might cause errors in the application. To correct this you can split the IAnimal interface into two. IAnimalSpeak and IAnimalSleep. The modified design is shown ...