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

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

ID: 3577117 • Letter: D

Question

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.0 for both width and height. A no-arg constructor that creates a default rectangle. A constructor that creates a rectangle with a specified width and height. A method named getArea() that returns the area of a rectangle. A method named getPerimeter() that returns the perimeter. The main method in your program should do the following things: • Create the first rectangle using the no-arg constructor. • Create a second rectangle using the constructor’s arguments to set the width to 4.0 and the height to 40.0. • Print out the area of the first rectangle. • Print out the perimeter of the second rectangle.

Explanation / Answer

RectangleTest.java


public class RectangleTest {

   public static void main(String[] args) {
       Rectangle r1 = new Rectangle();
       Rectangle r2= new Rectangle(4.0, 40.0);
       System.out.println("Default constructor rectangle area is "+r1.getArea());
       System.out.println("Default constructor rectangle perimeter is "+r1.getPerimeter());
       System.out.println("Rectangle area is "+r2.getArea());
       System.out.println("Rectangle perimeter is "+r2.getPerimeter());
   }

}

Rectangle.java


public class Rectangle {
   private double width=1.0, height=1.0;
   public Rectangle(){
      
   }
   public Rectangle (double w, double h){
       width = w;
       height = h;
   }
   public double getArea(){
       return width * height;
   }
   public double getPerimeter(){
       return 2 * (width + height);
   }
}

Output:

Default constructor rectangle area is 1.0
Default constructor rectangle perimeter is 4.0
Rectangle area is 160.0
Rectangle perimeter is 88.0

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