Write a Java class called Rectangle that represents a rectangular two-dimensional region. It should have following 4 fields:
int x (x-coordinate for its top left corner)
int y (y coordinate for its top left corner)
double height (height of the rectangle)
double width (width of the rectangle)
Your rectangle objects should have the following methods:
public Rectangle(int newx, int newy, int newwidth, int newheight)
Constructor that initializes the x-coordinate, y-coordinate for the top left corner and its width and height.
public double getHeight() (returns the rectangles height)
public double getWidth() (returns the rectangle's width)
public int getX() (returns the rectangle's x-coordinates)
public int getY() (returns the rectangle's y-coordinate)
public String toString() (returns a string representation of this rectangle such as "Rectangle [x=2, y=13, height=14, width = 5]")
public double area() (returns area of rectangle)
public double perimeter() (returns perimeter of the rectangle)
Write a client program called RectangleClient that creates objects of theRectangle class called rect1 and rect2. Assign values to the field of these objects. Print out these rectangle objects using toString method, and then print out their area and perimeter.
class Rectangle { private int x, y; private double height, width; public Rectangle(int newx, int newy, int newwidth, int newheight) { x = newx; y = newy; width = newwidth; height = newheight; } public int getX() { return x; } public int getY() { return y; } public double getHeight() { return height; } public double getWidth() { return width; } @Override public String toString() { return "Rectangle [x=" + x + ", y=" + y + ", height=" + height + ", width = " + width + "]"; } public double area() { return height * width; } public double perimeter() { return 2*(height+width); } } class RectangleClient { public static void main(String[] args) { Rectangle rect1 = new Rectangle(0, 0, 7, 4), rect2 = new Rectangle(3, -5, 7, 10); System.out.println("Rectangle 1: " + rect1); System.out.println("Area: " + rect1.area()); System.out.println("Perimeter: " + rect1.perimeter()); System.out.println("Rectangle 2: " + rect2); System.out.println("Area: " + rect2.area()); System.out.println("Perimeter: " + rect2.perimeter()); } }
Get Answers For Free
Most questions answered within 1 hours.