官术网_书友最值得收藏!

Liskov Substitution Principle

The Liskov Substitution Principle states that:

Child classes should never break the parent class' type definitions.

According to this principle, a subclass should override the parent class's methods in a way that does not break functionality from a client's point of view.

According to this principle, if a class is extending another class, the functionality of the child class should not conflict with that of its parent.

We can demonstrate this with the following example:

public class Rectangle { 
   private double length; 
   private double height; 
 
 
   public void setLength(double length) { 
       this.length = length; 
   } 
 
   public void setHeight(double height) { 
       this.height = height; 
   } 
 
   public double getLength() { 
       return length; 
   } 
 
   @Override 
   public double getHeight() { 
       return height; 
   } 
 
   public double getArea() { 
       return (length * height); 
   } 
} 

Here we have a rectangle. As we know, a square is also a type of rectangle, so it can extend the Rectangle class. Also we know that the height and the width of the square have to be the same so the getter can be written like this:

public class Square extends Rectangle { 
 
   @Override 
   public void setHeight(double height) { 
       this.length = height; 
       this.height = height; 
   } 
 
   @Override 
   public void setLength(double length) { 
       this.length = length; 
       this.height = length; 
   } 
} 

As can be seen from the preceding definition, we can get a rectangle also from the square implementation.

So now let's get an instance of Rectangle from the Square class:

Rectangle r = new Square(); 
r.setHeight(5); 
r.setLength(10); 

Now if we try to get the area, we will get 100 instead of 50, as a square has both the same length and height, which is not the case with a rectangle, and this violates the Liskov Substitution Principle.

A simple example of the Liskov Substitution Principle would be a List and ArrayList. An ArrayList implements a List but it does not change the basic functionality of the List.

主站蜘蛛池模板: 泽州县| 若尔盖县| 确山县| 酒泉市| 泾源县| 延长县| 岳西县| 澎湖县| 保康县| 天镇县| 全南县| 昭觉县| 黄骅市| 瑞金市| 思茅市| 密云县| 大石桥市| 武清区| 天津市| 沧源| 昌图县| 河北省| 民和| 漳平市| 景德镇市| 桐乡市| 龙口市| 襄汾县| 凤翔县| 固原市| 万安县| 吉木乃县| 特克斯县| 山阳县| 马尔康县| 和平县| 金门县| 军事| 平塘县| 寿光市| 尉犁县|