Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

union

Language/Type: Java classes fields instance methods
Related Links:
Author: Marty Stepp

Suppose that you are provided with a pre-written class Rectangle as described below. (The headings are shown, but not the method bodies, to save space.) Assume that the fields, constructor, and methods shown are already implemented. You may refer to them or use them in solving this problem if necessary.

// A Rectangle stores an (x, y) coordinate of its top/left corner, a width and height.
public class Rectangle {
    private int x;
    private int y;
    private int width;
    private int height;

    // Constructs a new Rectangle with the given x,y,w,h.
    public Rectangle(int x, int y, int w, int h)

    // returns the field values
    public int getX()
    public int getY()
    public int getWidth()
    public int getHeight()

    // example: {(5,12), 4x8}
    public String toString()

    // your method would go here

}

Write an instance method named union that will be placed inside the Rectangle class to become a part of each Rectangle object's behavior. The union method accepts another rectangle r as a parameter and turns this rectangle into the union of itself and r ; that is, modifies the fields so that they represent the smallest rectangular region that completely contains both this rectangle and r .

For example, if the following objects are declared in client code:

Rectangle rect1 = new Rectangle(5, 12, 4, 6);
Rectangle rect2 = new Rectangle(6,  8, 5, 7);
Rectangle rect3 = new Rectangle(14, 9, 3, 3);
Rectangle rect4 = new Rectangle(10, 3, 5, 8);

The following calls to your method would modify the objects' state as indicated in the comments:

rect1.union(rect2);   // {(5, 8), 6x10}
rect4.union(rect3);   // {(10, 3), 7x9}
Type your solution here:


This is a partial class problem. Submit code that will become part of an existing Java class as described. You do not need to write the complete class, just the portion described in the problem.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.