a) Write a class called Square, as a subclass of Rectangle. Convince yourself that Square can be modeled as a subclass of Rectangle. Square has no instance variable, but inherits the instance variables width and length from its superclass Rectangle.
· Provide the appropriate constructors (as shown in the class diagram). Hint:
public Square(double side) {
super(side, side); // Call superclass Rectangle(double, double)
}
· Override the toString() method to return "A Square with side=xxx, which is a subclass of yyy", where yyy is the output of the toString() method from the superclass.
· Do you need to override the getArea() and getPerimeter()? Try them out.
· Override the setLength() and setWidth() to change both the width and length, so as to maintain the square geometry.
public class Square extends Rectangle {
public Square(double side) {
super(side, side);
}
@Override
public void setLength(double length) {
super.setWidth(length);
super.setLength(length);
}
@Override
public void setWidth(double width) {
setLength(width);
}
@Override
public String toString() {
return "A Square with side=" + getWidth() + ", which is a subclass of " + super.toString();
}
}
Comments
Leave a comment