徐州提供网站建设报价表,手机微网站怎么做,重庆城市建设网站,个人网站建设案例课堂里氏替换原则#xff08;Liskov Substitution Principle#xff09;是面向对象设计中的一个基本原则#xff0c;它是由Barbara Liskov提出的。 如果对于每一个类型为Apple的对象1#xff0c;都有类型为fruit的对象2#xff0c;使得以fruit定义的所有程序 P 在所有的对象1都…里氏替换原则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 {Overridepublic void setWidth(int width) {this.width width;this.height width;}Overridepublic void setHeight(int height) {this.width height;this.height height;}
}public class LiskovSubstitutionPrincipleExample {public static void main(String[] args) {//将子类对象Square的值赋值给父类对象rectangleRectangle rectangle new Square();rectangle.setWidth(5);rectangle.setHeight(10);System.out.println(Area: rectangle.calculateArea()); // 输出 100而不是预期的 50}
}上述实例违背了里氏替换原则如下所示 使用子类对象square的值赋值给rectangle对象程序出现了错误的计算结果因此子类对象没有完全代替父类对象的行为违背了里氏替换原则
//该调用顺序下---输出100
rectangle.setWidth(5);
rectangle.setHeight(10);//该调用顺序下---输出25
rectangle.setHeight(10);
rectangle.setWidth(5);