Add the following method to your Rectangle class:
public Rectangle union(Rectangle rect)
Returns a new Rectangle that represents the area occupied by the tightest bounding box that contains both this Rectangle and the given other Rectangle.
package classes; public class Rectangle { int x; int y; int width; int height; Point point;
// initialize the constructor with point, width and heightpublic Rectangle(Point p, int width, int height) { this.point = p; this.width = width; this.height = height; }
// one more constructor with x and y values and height and widthpublic Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } // newly added union method wich takes rectanle class as parameter public Rectangle union(Rectangle rec) { int x1 = Math.min(x, rec.x); int y1 = Math.min(y, rec.y); int y2 = Math.max(y + height, rec.y + rec.height); int x2 = Math.max(x + width, rec.x + rec.width); return new Rectangle(x1, y1, x2 - x1, y2 - y1); } public boolean contains(int x, int y) { return this.x <= x && x <= this.x + width && this.y <= y && y <= this.y + height; } public boolean contains(Point p) { return contains(p.getX(), p.getY()); }
// getter and setterspublic int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } @Override public String toString() { return "[Rectangle x = " + this.x + ", y = " + this.y + ", width = " + width + ", height = " + height + "]"; } public static void main(String[] args) { Rectangle rec = new Rectangle(4, 6, 8, 5); Rectangle rec1 = new Rectangle(8, 5, 7, 5); System.out.println("New Rectangle formed: " + rec.union(rec1)); } }
Output:
New Rectangle formed: [Rectangle x = 4, y = 5, width = 11, height = 6]