A Square Is Not a Rectangle
The following example, taken from an introductory text in object oriented programming, demonstrates a common flaw in object oriented design. Can you spot it?
public class Rectangle {
private double width;
private double height;
public void setWidth(double width) {
this.width = width;
}
public void setHeight(double height) {
this.height = height;
}
public double getHeight() {
return this.height;
}
public double getWidth() {
return this.width;
}
public double getPerimeter() {
return 2*width + 2*height;
}
public double getArea() {
return width * height;
}
}
public class Square extends Rectangle {
public void setSide(double size) {
setWidth(size);
setHeight(size);
}
}
(I’ve changed the language and rewritten the code to protect the guilty.)
Read the rest of this entry »