But on other hand, we have to implement functionality of another transport device called Bicycle, then we can derive this class from TransportationDevice class and implement functionality for startMovement() as Bicycle can move. If we have to implement functionality of Car, we can derive a child class out of this and add concrete implementation of both methods as car has engine so we can start it and car can also do movement. It also has startEngine() and startMovement() methods. ![]() Suppose we have a parent class called " TransportationDevice" with attributes like speed and name. Lets understand with example where we violate Liskov Substitution Principle. This principle will help you to decide the base class and sub class you have selected in your architecture, if they belong to the same hierarchy or not. This principle is there to help you to implement OCP in correct way to ensure that you can change one part of your system without breaking other parts. The Liskov Substitution principle is an extension of Open Closed Principle. This is also called as "Strong Behavioral Subtyping". If child class is not able to do the thing which parent class can do, then its not a correct hierarchy and we can not substitute child class for their parent class. Means if My parent class object is able to do something, then all the child classes objects should also be able to do that thing. ![]() That requires the objects of your subclasses to behave in the same way as the objects of your superclass. The principle defines that, " objects of a superclass shall be replaceable with objects of its subclasses without breaking the application". In simple words as stated by Robert C Martin, this principle states that: The functions that use pointers of reference to base classes must be able to use objects of derived classes without knowing it. This principle is written by Barbara Liskov in her conference keynote "Data Abstraction" in 1987. What is Liskov Substitution Principle(LSP) ? Inheritance can also be read as "Is A" relationship, eg. We have seen it in earlier article with Shape class with its derived classes like Rectangle, Circle etc. ![]() We have seen that with the help of "polymorphism" we are able to invoke derived class methods using a base class reference variable at run time. To assure, that we are not breaking other parts of system, our code need to follow the Liskov Substitution Principle. But following this OCP principle alone, may not be enough to ensure that, change in one part of system wont break other parts of system. This principle helps us to maintain our code, make reusable and extendable components. We have seen " Open Closed Principle" in previous article.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |