The SOLID principles focus on achieving code
that is maintainable, robust, and reusable and in this blog, we will
discuss the Liskov Substitution Principle.
The derived classes
should be perfectly substitutable for their base classes.
Here is an example of Base and derived class:
Rectangle class is base class for Square
class and Base class have height, width field and Area function to calculate the
area.
public class Rectangle
{
public int Height
{ get; protected set; }
public int Width
{ get; protected set; }
public virtual void SetWidth(int width)
{
Width = width;
}
public virtual void SetHeight(int height)
{
Height = height;
}
public int Area()
{
return Width * Height;
}
}
public class Square : Rectangle
{
public override void SetHeight(int height)
{
Height = height;
Width = height;
}
public override void SetWidth(int width)
{
Height = width;
Width = width;
}
}
Now we will see How the Square Class object
will replace the Rectangle base class object, without changing code and can
able to calculate the Area of SQUARE by using base class function.
1st example - we instantiate a
rectangle object and set height and width of rectangle and call Area () method
to get area of rectangle.
Rectangle rect = new Rectangle();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); //
Actual value : 20
2nd example- we are instantiating Square object
and assigned to Rectangle object and setting height and width of rectangle and
call Area () method to get area of square.
Rectangle rect = new Square();
rect.SetHeight(10);
rect.SetWidth(2);
int val = rect.Area(); //
Actual value : 4
Now in 2nd example, rect
holds reference of the type of Square Object, so it’s result is different (area
value: 4) and it replace the instance/object of the Rectangle with Square type
Other Links:
Thanks for Visiting!!
No comments:
Post a Comment