Add the following constructor to your Rectangle class:
public Rectangle(Point p, int width, int height)
Construct a new Rectangle whose top-left corner is specified by the given Point and with the given width and height.
// package classes;
public class Rectangle {
int x;
int y;
int width;
int height;
Point point;
// newly added constructor
// initialize the constructor with point, width and height
public 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 width
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
// getter and setters
public 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 + "]";
}
// driver method
public static void main(String[] args) {
Point pnt = new Point(4, 3);
System.out.println("New Rectangle: "+new Rectangle(pnt, 8, 5));
}
}
Output:
new Rectangle: [Rectangle x = 4, y = 3, width = 8, height = 5]