Define a class named Rectangle. A Rectangle object stores an (x, y) coordinate o
ID: 3821287 • Letter: D
Question
Define a class named Rectangle. A Rectangle object stores an (x, y) coordinate of its top/left corner (0, 0), a width, and a height. Each Rectangle object should have the following public methods:
Rectangle (x, y, width, height) Constructs a new rectangle whose top-left corner is specified by the given coordinates and with the given width and height. getX Returns this rectangle's leftmost x-coordinate. get Y Returns this rectangle's top y-coordinate. getWidth Returns this rectangle's width. get Height Returns this rectangle's height. toString Returns a String representation of this rectangle, such as "Rectangle [x 1, y 2, width 3, height 4] TT contains (x, y) Returns whether the given Point's (x, y) coordinates lie inside the bounds of this rectangle. equals (rect) Returns whether the given other rectangle rect is a rectangle with the same xly coordinates, width, and height as this rectangle getArea (rect) Returns an area of this rectangle. (Ref. area width height) moves (dx dy) Moves the rectangle by dx and dyExplanation / Answer
Hi, Please find my implementation of Rectangle class.
Please let me know in case of any issue.
/**
* The Rectangle class stores and manipulates
* data for a rectangle.
*/
public class Rectangle
{
private double height;
private double width;
private double x, y;
/**
* Constructor
*/
public Rectangle(double x, double y, double height, double width)
{
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}
/**
* The getX method returns the left most x-coordinate
* stored in the x field.
*/
public double getX(){
return x;
}
/**
* The getY method returns the top y coordinatw
* stored in the y field.
*/
public double getY(){
return y;
}
/**
* The getLength method returns the value
* stored in the length field.
*/
public double getHeight()
{
return height;
}
/**
* The getWidth method returns the value
* stored in the width field.
*/
public double getWidth()
{
return width;
}
/**
* The getArea method returns the value of the
* length field times the width field.
*/
public double getArea()
{
return height * width;
}
public boolean contains(double x, double y){
if(this.x <= x && x <= (this.x+width) && y <= this.y && y>=(this.y-height))
return true;
else
return false;
}
public boolean equals(Rectangle rect) {
if(x == rect.x && y == rect.y && height == rect.height && width == rect.width)
return true;
else
return false;
}
public String toString() {
return "Rectangle[x="+x+", y="+y+", width="+width+", height="+height+"]";
}
public void move(double dx, double dy){
x = x + dx;
y = y + dy;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.