里氏替换原则~

里氏替换原则 (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);      
相关推荐
lixzest1 分钟前
C++应用开发转到大模型应用开发路径
开发语言·c++·人工智能·python
BingoGo1 分钟前
2026 年 PHP 的三大优势 这门"老将"为何依然重要
后端·php
小萌新大梦想6 分钟前
SpringCloud 概述翻译
后端·spring·spring cloud
JaguarJack6 分钟前
2026 年 PHP 的三大优势 这门"老将"为何依然重要
后端·php·服务端
sxlishaobin6 分钟前
设计模式之享元模式
java·设计模式·享元模式
IT_陈寒6 分钟前
Python 3.12 新特性实战:5个让你的代码效率提升30%的技巧
前端·人工智能·后端
黎明晓月7 分钟前
Redis容器化(Docker)
java·redis·docker
Wpa.wk8 分钟前
接口自动化测试 - REST-assure小练习(Java版-分层)
java·开发语言·经验分享·python·自动化·接口自动化·po
予枫的编程笔记9 分钟前
深度解析Logstash与Beats:Elastic Stack数据采集处理双核心
java·elasticsearch·logstash·beats
张人玉9 分钟前
C#WPF页面布局及其属性
开发语言·c#·wpf