Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1- Design a class named Rectangle to represent a rectangle. The class contains:

ID: 3529517 • Letter: 1

Question

1- Design a class named Rectangle to represent a rectangle. The class contains: ? Two double data fields named width and height that specify the width and height of the rectangle. The default values are 1 for both width and height. ? A no-arg constructor that creates a default rectangle. ? A constructor that creates a rectangle with the specified width and height. ? A method named getArea() that returns the area of this rectangle. ? A method named getPerimeter() that returns the perimeter. Draw the UML diagram for the class. Implement the class. Write a test program that creates two Rectangle objects

Explanation / Answer

public class RectangleDemo { private class Rectangle { private double height; private double width; private String color; public Rectangle(double wid, double high){ height = high; width = wid; } public Rectangle(){ height = 1; width = 1; color = "White"; } public void setHeight(double high){ height = high; } public void setWidth(double wid){ width = wid; } public void setColor(String col){ color = col; } public double getArea(){ return height*width; } public double getPerimeter(){ return 2*(height + width); } public void getColor(){ System.out.println("Color is: " + color +" "); return; } } public class RectangleDemo { public static void main(String[] args){ Rectangle box1 = new Rectangle(); Rectangle box2 = new Rectangle(4, 40); Rectangle box3 = new Rectangle(3.5, 35.9); String Color = "Red"; box1.setColor(Color); box2.setColor(Color); box3.setColor(Color); box1.getColor(); box2.getColor(); box3.getColor(); System.out.println("The perimeter of the first box is: " + box1.getPerimeter() + " "); System.out.println("The perimeter of the second box is: " + box2.getPerimeter() + " "); System.out.println("The perimeter of the third box is: " + box3.getPerimeter() + " "); System.out.println("The area of the first box is: " + box1.getArea() + " "); System.out.println("The area of the second box is: " + box2.getArea() + " "); System.out.println("The area of the third box is: " + box3.getArea() + " "); } }