里氏替换原则~

里氏替换原则 (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);      
相关推荐
Wy_编程几秒前
Go语言中的指针
开发语言·后端·golang
沪漂阿龙7 分钟前
字节跳动大模型面试题深度拆解:项目深挖、SFT 与 RLHF、Claude Code、记忆机制、并发锁与手撕题全攻略
人工智能·面试
GetcharZp11 分钟前
RabbitMQ 深度全解析,从 Docker 部署到 Go 语言高并发实战!
后端
不想写代码的星星13 分钟前
C++协程从入门到放弃?不,是从入门到手搓调度器
开发语言·c++
redaijufeng18 分钟前
C++构造函数详解:从基础原理到实际应用
java·jvm·c++
lolo大魔王21 分钟前
Go语言数据库操作之GORM框架从入门到生产实战(完整版)
开发语言·数据库·golang
yuzhiboyouye31 分钟前
VO一般java后端怎么转换成前端想要的数据
java·前端·状态模式
一 乐34 分钟前
学院教学工作量统计|基于java+ vue学院教学工作量统计管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·学院教学工作量统计系统
迷藏49439 分钟前
【无标题】
java·数据库·oracle
cndes43 分钟前
Pycharm的虚拟环境设置问题
开发语言·python