In: Computer Science
Design and implement a class Rectangle to represent a rectangle. You should provide two Constructors for the class, the first being the default constructor and the second which takes the basic dimensions and sets up the private member variables with the appropriate initial values. Methods should be provided that allow a user of the class to find out the length, width, area and perimeter of the shape plus a toString()method to print the values of the basic dimensions. Now implement a class called Square that represents a square. Class Square must be derived from Rectangle. Make sure you override toString().
Here is code:
Rectangle.java:
class Rectangle {
protected double width;
protected double height;
public Rectangle() {
this.width = this.height = 0;
}
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
public String toString() {
return " area " + String.format("%.2f", getArea()) +
" and perimeter " + String.format("%.2f", getPerimeter());
}
}
Square.java:
class Square extends Rectangle {
public Square(double side) {
this.width = this.height = side;
}
}
ShapeTester.java:
public class ShapeTester{
public static void main(String[] args) {
Rectangle r = new Rectangle(5,9);
Square s = new Square(9);
System.out.println("Rectangle : ");
System.out.println(r.toString());
System.out.println("Square :");
System.out.println(s.toString());
}
}
Output: