• 里氏替换原则~


    里氏替换原则(Liskov Substitution Principle)是面向对象设计中的一个基本原则,它是由Barbara Liskov提出的。

    如果对于每一个类型为Apple的对象1,都有类型为fruit的对象2,使得以fruit定义的所有程序 P 在所有的对象1都替换成2时,程序 P 的行为没有发生变化,那么类型 Apple是类型 fruit 的子类型。

    简单点说就是子类可以替换父类并且不会影响程序的正确性,这个原则强调了子类的可替换性和灵活性

    举例:

    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
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    上述实例违背了里氏替换原则,如下所示:

    在这里插入图片描述

    使用子类对象square的值赋值给rectangle对象,程序出现了错误的计算结果,因此子类对象没有完全代替父类对象的行为,违背了里氏替换原则

    //该调用顺序下---输出100
    rectangle.setWidth(5);
    rectangle.setHeight(10);
    
    //该调用顺序下---输出25
    rectangle.setHeight(10);
    rectangle.setWidth(5);      
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
  • 相关阅读:
    资深测试面试-参考一下
    mysql不区分大小写配置
    rman 如何记录日志及如何对rman命令进行debug
    限流算法之----滑动窗口
    记一次 .NET 某电力系统 内存暴涨分析
    hadoopHa集群namenode起不来的原因(1)
    美国FBA海运有哪几种渠道
    computed计算属性
    Android开发之——Jetpack Compose入门(01)
    JAVA毕业设计考研经网站系统计算机源码+lw文档+系统+调试部署+数据库
  • 原文地址:https://blog.csdn.net/m0_64365419/article/details/132862065