
Liskov substitution principle (LSP) – SOLID
This principle states that any of the child classes should not break the parent class's type definitions or, in other words, derived classes should be substitutable for their base classes.
Let's first understand the violation of substitution principle, and then we see how we can resolve the same by taking our earlier example of account classes as LSP is a prime enabler of OCP:
Let's assume that withdrawal from kids account is not allowed, unlike general account. As you see in the preceding class diagram, a withdraw method in the kids account class is a breach of LSP, so by introducing other withdrawable and non-withdrawable classes inherited from SavingsAccount class to handle non-withdrawable behavior, we can get rid of the breach and the subclass does not change the base class behavior:
So, the behavior of SavingsAccount is preserved while inheriting it for KidsAccount. The preceding code snippet proves the same.