详解Java设计模式编程中的里氏替换原则
|
定义1:如果对每一个类型为 T1的对象 o1,都有类型为 T2 的对象o2,使得以 T1定义的所有程序 P 在所有的对象 o1 都代换成 o2 时,程序 P 的行为没有发生变化,那么类型 T2 是类型 T1 的子类型。 例子:
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());
}
}
总结: 您可能感兴趣的文章:
(编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
