- Expert Android Programming
- Prajyot Mainkar
- 319字
- 2021-07-08 10:29:14
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.
- HTML5+CSS3王者歸來
- SPSS數據挖掘與案例分析應用實踐
- Modular Programming with Python
- 自己動手寫搜索引擎
- Effective C#:改善C#代碼的50個有效方法(原書第3版)
- 控糖控脂健康餐
- PostgreSQL技術內幕:事務處理深度探索
- 精通Python自然語言處理
- Learning JavaScript Data Structures and Algorithms
- Natural Language Processing with Java and LingPipe Cookbook
- Mastering Linux Security and Hardening
- Java并發編程之美
- 遠方:兩位持續創業者的點滴思考
- Scrapy網絡爬蟲實戰
- 虛擬現實建模與編程(SketchUp+OSG開發技術)