Add the following methods to your Rectangle class:
public boolean contains(int x, int y)
public boolean contains(Point p)
Returns whether the given Point or coordinates lie inside the bounds of this 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; } 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 the toStrinng to print our rectangle values@Override public String toString() { return "[Rectangle x = " + point.x + ", y = " + point.y + ", width = " + width + ", height = " + height + "]"; } public static void main(String[] args) { Point pnt = new Point(4, 3); Rectangle rec = new Rectangle(pnt, 8, 5); int x1 = 5; int y1 = 6; System.out.println("New Rectangle: " + rec); System.out.println("does New Rectangle contains " + pnt + ": " + rec.contains(pnt)); System.out.println("New Rectangle contains (" + x1 + "," + y1 + "):" + rec.contains(x1, y1)); } }
Output:
New Rectangle: [Rectangle x = 4, y = 3, width = 8, height = 5]
does New Rectangle contains (4,3): true
New Rectangle contains (5,6):false