里氏替换原则~

里氏替换原则 (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);      
相关推荐
yuuki23323321 分钟前
【数据结构】栈
c语言·数据结构·后端
草莓熊Lotso22 分钟前
C++ STL set 系列完全指南:从底层原理、核心接口到实战场景
开发语言·c++·人工智能·经验分享·网络协议·算法·dubbo
珹洺26 分钟前
Java-Spring实战指南(三十四)Android Service实现后台音乐播放功能
android·java·spring
咖啡の猫2 小时前
搭建Python开发环境
开发语言·python
微学AI3 小时前
Rust语言的深度剖析:内存安全与高性能的技术实现操作
java·安全·rust
程序猿小蒜3 小时前
基于springboot的共享汽车管理系统开发与设计
java·开发语言·spring boot·后端·spring·汽车
lsp程序员0103 小时前
使用 Web Workers 提升前端性能:让 JavaScript 不再阻塞 UI
java·前端·javascript·ui
听风吟丶4 小时前
Java 8 Stream API 高级实战:从数据处理到性能优化的深度解析
开发语言·python
q***46525 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
hygge9995 小时前
Spring Boot + MyBatis 整合与 MyBatis 原理全解析
java·开发语言·经验分享·spring boot·后端·mybatis