![]() Suppose a book store asks us to add a new type of book delivery functionality in the application. I am not explaining this example as you will find it very easily from too many sources. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. The Square class always assumes that the width is equal with the height. We can also say that subclasses must fulfil a contract defined by the base class.Ī typical example that violates LSP is a Square class that derives from a Rectangle class. It helps us conform to the “is-a” relationship. This avoids overuse/misuse of inheritance. Why is it required to follow Liskov Substitution Principle? The only thing is that every subclass or derived class should be substitutable for their parent or base class. The definition of it might be a bit complex, but in fact, it is quite easy. Imagine a derived class throwing an exception that the superclass does not throw, or if a derived class has some unexpected side effects. In general, if a subtype of the super type does something that the client of the super type does not expect, then this is in violation of LSP. To be a true behavioral subtype, the subclass must not only implement the base class’s methods and properties, but also stick to its implied behavior. The specific functionality of the subclass may be different, but must conform to the expected behavior of the base class. LSP applies to inheritance hierarchies, specifying that you should design your classes so that client dependencies can be substituted with subclasses without the client knowing about the change.Īll subclasses must, therefore, operate in the same manner as their base classes. ![]() Basically, derived classes should never do less than their base class. Therefore, a child class should never change the characteristics of its parent class (such as the argument list and return types). In Layman’s terms, it states that an object of a superclass should be replaceable by objects of its subclasses without causing issues in the application. “Derived types must be completely substitutable for their base types” Simply put, if class A is a subtype of class B, then we should be able to replace objects of B with objects of A (i.e., objects of type A may substitute objects of type B) without changing the behavior (correctness, functionality, etc.) of our program.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |