里氏替换原则~

里氏替换原则 (Liskov Substitution Principle)是面向对象设计中的一个基本原则,它是由Barbara Liskov提出的。

如果对于每一个类型为Apple的对象1,都有类型为fruit的对象2,使得以fruit定义的所有程序 P 在所有的对象1都替换成2时,程序 P 的行为没有发生变化,那么类型 Apple是类型 fruit 的子类型。

简单点说就是子类可以替换父类并且不会影响程序的正确性,这个原则强调了子类的可替换性和灵活性。

举例:

java 复制代码
package Reaplcetest;
class Rectangle {
    protected int width;
    protected int height;

    public void setWidth(int width) {
        this.width = width;
    }

    public void setHeight(int height) {
        this.height = height;
    }

    public int calculateArea() {
        return width * height;
    }
}

class Square extends Rectangle {
    @Override
    public void setWidth(int width) {
        this.width = width;
        this.height = width;
    }

    @Override
    public void setHeight(int height) {
        this.width = height;
        this.height = height;
    }
}

public class LiskovSubstitutionPrincipleExample {
    public static void main(String[] args) {
       //将子类对象Square的值赋值给父类对象rectangle
        Rectangle rectangle = new Square();
        rectangle.setWidth(5);
        rectangle.setHeight(10);
        System.out.println("Area: " + rectangle.calculateArea()); // 输出 100,而不是预期的 50
    }
}

上述实例违背了里氏替换原则,如下所示:

使用子类对象square的值赋值给rectangle对象,程序出现了错误的计算结果,因此子类对象没有完全代替父类对象的行为,违背了里氏替换原则

java 复制代码
//该调用顺序下---输出100
rectangle.setWidth(5);
rectangle.setHeight(10);

//该调用顺序下---输出25
rectangle.setHeight(10);
rectangle.setWidth(5);      
相关推荐
敲敲了个代码3 小时前
从硬编码到 Schema 推断:前端表单开发的工程化转型
前端·javascript·vue.js·学习·面试·职场和发展·前端框架
想回家的一天3 小时前
ECONNREFUSED ::1:8000 前端代理问题
开发语言
cike_y3 小时前
Mybatis之解析配置优化
java·开发语言·tomcat·mybatis·安全开发
WanderInk3 小时前
刷新后点赞全变 0?别急着怪 Redis,这八成是 Long 被 JavaScript 偷偷“改号”了(一次线上复盘)
后端
Jay_Franklin4 小时前
SRIM通过python计算dap
开发语言·python
是一个Bug4 小时前
Java基础50道经典面试题(四)
java·windows·python
Slow菜鸟4 小时前
Java基础架构设计(三)| 通用响应与异常处理(分布式应用通用方案)
java·开发语言
吴佳浩5 小时前
Python入门指南(七) - YOLO检测API进阶实战
人工智能·后端·python
消失的旧时光-19435 小时前
401 自动刷新 Token 的完整架构设计(Dio 实战版)
开发语言·前端·javascript
wadesir5 小时前
Rust中的条件变量详解(使用Condvar的wait方法实现线程同步)
开发语言·算法·rust