// Each Rectangle object represents a 2D rectangle with a // top-left x/y coordinate, width, and height. public class Rectangle { private int x; private int y; private int width; private int height; // Constructs a new rectangle public Rectangle(int initialX, int initialY, int initialWidth, int initialHeight) { x = initialX; y = initialY; width = initialWidth; height = initialHeight; } // Returns this rectangle's leftmost x coordinate. public int getX() { return x; } // Returns this rectangle's topmost y coordinate. public int getY() { return y; } // Returns this rectangle's width. public int getWidth() { return width; } // Returns this rectangle's height. public int getHeight() { return height; } // Returns the area (w x h) of this rectangle. public int getArea() { return width * height; } // Returns a text representation of this rectangle. public String toString() { return "Rectangle[x=" + getX() + ",y=" + getY() + ",w=" + width + ",h=" + height + "]"; } // Returns whether the given point is contained within this rectangle. public boolean contains(Point p) { return getX() <= p.getX() && p.getX() < (getX() + width) && getY() <= p.getY() && p.getY() < (getY() + height); } // Returns whether the given rectangle is entirely contained in this rectangle. public boolean contains(Rectangle r) { return getX() <= r.getX() && r.getX() + r.getWidth() < (getX() + width) && getY() <= r.getY() && r.getY() + r.getHeight() < (getY() + height); } // Turns this rectangle into the smallest area that contains itself and rect. public void union(Rectangle r) { // find the union's bounds int left = Math.min(getX(), r.getX()); int top = Math.min(getY(), r.getY()); int right = Math.max(getX() + width, r.getX() + r.getWidth()); int bottom = Math.max(getY() + height, r.getY() + r.getHeight()); x = left; y = top; width = right - left; height = bottom - top; } }