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

Use Java for the following: Design and implement a class named Rectangle to repr

ID: 663260 • Letter: U

Question

Use Java for the following:

Design and implement 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 and then implement the class. Write a test program that creates two Rectangle objects

Explanation / Answer

Below is the solution:

class Rectangle
{
protected double width;
protected double height;

Rectangle()
{
width=1;
height=1;
}

Rectangle(double w, double h)
{
this.width=w;
this.height=h;
}

public double getArea()
{
return (width*height);
}
public double getPerimeter()
{
return (2*(width+height));
}

public double getWidth() {
   return width;
}

public void setWidth(double width) {
   this.width = width;
}

public double getHeight() {
   return height;
}

public void setHeight(double height) {
   this.height = height;
}

}

public class TestRectangle
{
   public static void main(String args[])
   {
Rectangle r1=new Rectangle(4,40);
Rectangle r2=new Rectangle(3.5,35.9);

System.out.println("Rectangle 1 with (4,40) ");
System.out.println(" Width: "+r1.getWidth());
System.out.println(" Height: "+r1.getHeight());
System.out.println(" Area: "+r1.getArea());
System.out.println(" Perimeter: "+r1.getPerimeter());

System.out.println("Rectangle 2 with (3.5,35.9) ");
System.out.println(" Width: "+r2.getWidth());
System.out.println(" Height: "+r2.getHeight());
System.out.println(" Area: "+r2.getArea());
System.out.println(" Perimeter: "+r2.getPerimeter());
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote