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.
class Square extends Rectangle {
public Square(int side) {
super(side, side);
System.out.println("Square Constructor");
}
/***
* area - prints "Square Area" and returns the area of the Square
*Â
* @return
*/
public int area() {
System.out.println("Square Area");
return this.getLength() * this.getWidth();
}
/**
* perimeter - prints "Square Perimeter" and returns the perimeter of the Square
*Â
* @return
*/
public int perimeter() {
System.out.println("Square Perimeter");
return 2 * (this.getLength() + this.getWidth());
}
/**
* @param length the length to set
*/
public void setLength(int side) {
super.setLength(side);
}
/**
* @param width the width to set
*/
public void setWidth(int side) {
super.setWidth(side);
}
public String toString() {
return "A Square with side="+this.getLength()+", which is a subclass of "+super.toString();
}
}
Comments
Leave a comment