设计模式原则(2):里氏替换原则
发布时间:2020-05-22 21:06:59 所属栏目:程序设计 来源:互联网
导读:里氏替换原则:所有引用基类的地方必须能透明地使用其子类的对象。 意思就是说,一个地方引用了父类,程序可以正常运行,如果把引用父类的地方换成子类,这个程序也应该能够正常运行。 例子: public class Rectangle {int width;int height;public Rectangle
里氏替换原则:所有引用基类的地方必须能透明地使用其子类的对象。
意思就是说,一个地方引用了父类,程序可以正常运行,如果把引用父类的地方换成子类,这个程序也应该能够正常运行。
public class Rectangle { int width; int height; public Rectangle(int w,int h){ width = w; height = h; } public int getArea(){ return width*height; } } public class Square extends Rectangle { public Square(int w,int h) { super(w,h); } public int getArea(){ return width*width; } } public class Test { public static void main(String[] args) { Rectangle rectangle = new Rectangle(10,20); // Square rectangle = new Square(10,20); System.out.println("面积:"+rectangle.getArea()); } } 如果我们把长方形类Rectangle替换为正方形类Square,那么求出的面积就不正确了,原因是我们继承的时候重写了父类的getArea方法。这是违背里氏替换原则的。 当然,这里只是举个例子,实际项目中我们不会这样修改的。 总结: 1. 尽量不要重写父类方法,而是增加自己特有的方法。 2.继承给程序设计带来巨大便利的同时,也带来了弊端。如果一个类被其他的类所继承,则当这个类需要修改时,必须考虑到所有的子类,并且父类修改后,所有涉及到子类的功能都有可能会产生BUG。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |