里氏替换原则要求子类能替换父类且不改变程序正确性,文中以图形面积计算为例,指出Square继承Rectangle会导致行为不一致,违反LSP;改进方案是让Rectangle和Square均继承自抽象类Shape,各自独立实现getArea方法,确保行为契约一致,从而符合LSP。

里氏替换原则(Liskov Substitution Principle, LSP)是面向对象设计中的重要原则之一,强调子类应该能够替换其父类出现在程序中的任何地方,并且不改变程序的正确性。这意味着子类不仅要继承父类的方法和属性,更要保持行为的一致性。下面通过一个实际例子来说明该原则的应用。
假设我们正在开发一个图形处理系统,需要计算不同图形的面积。定义一个基类 Shape,并让具体的图形如矩形、正方形继承它。
违反LSP的例子:
定义一个 Rectangle 类:
class Rectangle {
protected int width, height;
<pre class='brush:java;toolbar:false;'>public void setWidth(int width) {
this.width = width;
}
public void setHeight(int height) {
this.height = height;
}
public int getArea() {
return width * height;
}}
然后创建一个 Square 类继承 Rectangle,因为正方形是一种特殊的矩形:
class Square extends Rectangle {
public void setWidth(int width) {
super.setWidth(width);
super.setHeight(width);
}
<pre class='brush:java;toolbar:false;'>public void setHeight(int height) {
super.setHeight(height);
super.setWidth(height);
}}
问题出现在以下使用场景:
public static void testRectangle(Rectangle r) {
r.setWidth(5);
r.setHeight(4);
if (r.getArea() != 20)
System.out.println("面积计算错误!");
}
这个方法对普通 Rectangle 没问题,但传入 Square 实例时:
尽管语法上 Square 是 Rectangle 的子类,但行为不一致,导致程序逻辑出错 —— 这就违反了里氏替换原则。
要符合LSP,应避免让 Square 错误地扩展 Rectangle 的行为。可以采用组合或重构继承关系。
一种合理方式是:将 Shape 设为抽象类或接口,各图形独立实现:
abstract class Shape {
public abstract int getArea();
}
<p>class Rectangle extends Shape {
private int width, height;</p><pre class='brush:java;toolbar:false;'>public void setWidth(int width) { this.width = width; }
public void setHeight(int height) { this.height = height; }
public int getArea() { return width * height; }}
class Square extends Shape { private int side;
public void setSide(int side) { this.side = side; }
public int getArea() { return side * side; }}
此时,Rectangle 和 Square 都继承自 Shape,但在各自逻辑内保持一致性。任何接受 Shape 的方法都可以安全地调用 getArea(),无需关心具体类型。
基本上就这些。里氏替换原则提醒我们:继承不只是代码复用,更是行为契约的延续。设计时多考虑“能否安全替换”,能有效避免后期bug和扩展难题。
以上就是OOP中里氏替换原则的实际应用举例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号