里氏替换原则~

里氏替换原则 (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);      
相关推荐
Lear几秒前
【MySQL】索引失效10大场景详解:如何避免索引失效提升查询性能
后端
wearegogog1234 分钟前
DEA模型MATLAB实现(CCR、BCC、超效率)
开发语言·算法·matlab
Lear10 分钟前
【Spring】事务失效场景详解:原理、问题与解决方案
后端
小马爱打代码12 分钟前
Spring AI:文生图:调用通义万相 AI 大模型
java·人工智能·spring
郝学胜-神的一滴14 分钟前
Linux定时器编程:深入理解setitimer函数
linux·服务器·开发语言·c++·程序人生
摇滚侠17 分钟前
2025最新 SpringCloud 教程,网关功能、创建网关,笔记51、笔记52
java·笔记·spring cloud
cici1587418 分钟前
基于反向传播算法实现手写数字识别的MATLAB实现
开发语言·算法·matlab
又是忙碌的一天30 分钟前
Socket学习
java·学习·socket
青白菜30 分钟前
将Java程序打包成exe文件
后端
泉城老铁42 分钟前
springboot+vue 如何实现海康摄像头喊话功能
前端·vue.js·后端