Question 0-5

Define a new class Rect that can be used to create an object representing a rectangle. The constructor method for Rect should take two parameters, both doubles: the rectangle's width and the rectangle's height. The class should support the following object methods.

double getPerimeter() Returns the length of the rectangle's perimeter.
double getArea() Returns the area of the rectangle.
boolean canContain(Rect other) Returns true if other can fit within the rectangle. (in its current configuration or rotated 90 degrees).
public class Rect {
    // your answer here...


}

Solution

public class Rect {
    private double width;
    private double height;

    public Rect(double w, double h) {
        width = w;
        height = h;
    }

    public double getPerimeter() {
        return 2 * width + 2 * height;
    }

    public double getArea() {
        return width * height;
    }

    public boolean canContain(Rect other) {
        return (width >= other.width && height >= other.height)
            || (width >= other.height && height >= other.width);
    }
}

Back to Review for Midterm 0