I am studying liskov substitution principle
. It says sub classes should be proper replacement for the base classes
.
I read an example which I found at various places in the internet. A class Rectangle.java
with height, width
and their setter and getter methods
. A class Square.java
which requires only one attribute i.e length
. If we have Square.java extending Rectangle.java
then this is an violation of this principle. This is because the users of Rectangle.java
expect width
not to get affected if only height
is modified and vice-versa.
My doubts:
The situations we see where methods are just overridden with empty open and close braces in order to prevent the execution of default code written in the base class. Are such cases violation of this principle ?
This principle also says
inheritance
should not be used just for reusing the code. Does in case as below it is a bad practice and is this a violation of this principle ?
If a class Window.java is available from some Graphic library. Suppose it has all the code necessary to draw a window. Also suppose it has a toolbar when it is used and drawn. If the requirement is to create a window without toolbar.
Simply Creating a WindowWithoutToolBar.java extending Window.java and overriding the drawToolBarMethod() and leaving it with empty body solves the purpose.[May be just create toolbar and not draw it so as to avoid any exceptions occurring from other methods trying to access toolbar object] Is this a bad practice ?
Creating a whole new Window class without toolbar would have required to rewrite all the code already written in Window.java.
- In case of Numbers, If we have a class Integer.java with code in it for various arithmetic operations that can be done with an integer like squaring etc. If we have later need of NaturalNumber.java we can easily extend it from existing Integer.java and add checks to take only positive integers as input.
Now if we need AbsoluteNumber.java then in case we extend it from Integer.java does this violates this principle (in case Integer.java has some method as getValueAfterMultiplyByNegativeOne()) ?
Please provide your valuable feedback.
Regards,
Krishna Kumar
Window
andInteger
examples violate the Single Responsibility Principle. Adhering to Liskov Substitution will be more difficult when there are multiple responsibilities to substitute. - jaco0646