里氏替换原则~

里氏替换原则 (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);      
相关推荐
繁华似锦respect几秒前
C++ 无锁队列(Lock-Free Queue)详细介绍
linux·开发语言·c++·windows·visual studio
SXJR5 分钟前
CAP原则
java·后端·spring cloud·微服务
专注API从业者7 分钟前
Node.js/Python 调用淘宝关键词搜索 API:从接入到数据解析完整指南
开发语言·数据结构·数据库·node.js
爱学习的执念9 分钟前
2025年100道最新软件测试面试题,常见面试题及答案汇总
软件测试·软件测试工程师·面试
q***o37610 分钟前
【Spring Boot】统一数据返回
java·spring boot·后端
liu****11 分钟前
九.操作符详解
c语言·开发语言·数据结构·c++·算法
开心猴爷11 分钟前
Fiddler抓包工具详解,HTTPHTTPS调试、代理配置与接口分析实战教程
后端
人得思变~谁会嫌自己帅呢?11 分钟前
Java中的类加载器工作原理
java·开发语言
Dwzun13 分钟前
基于SpringBoot的共享单车调度系统【附源码+文档+部署视频+讲解)
java·数据库·vue.js·spring boot·后端·毕业设计·maven
青春男大13 分钟前
用向导创建SpringBoot项目
java·spring boot·后端