Part 1: Create a class called Rectangle that represents a standard, 2-dimensiona
ID: 3635602 • Letter: P
Question
Part 1: Create a class called Rectangle that represents a standard, 2-dimensional rectangle. Theclass should contain:
• Two double data fields named height and width. The default values for both should be 1.
• A no-argument constructor that creates the defaul rectangle.
• A constructor that creates a rectangle with a specified height and width.
• A method named getArea( ) that returns the area of the rectangle.
• A method named getPerimeter( ) that returns the perimeter of the rectangle.
Write a test program that creates two Rectangle objects, one with width 4 and height 40, and one
with width 3.5 and height 35.9. Display the width, height, area, and perimeter of each rectangle
in this order.
Explanation / Answer
public class Rectangle { private double height; private double width; public Rectangle() { this.height = 1.0; this.width = 1.0; } public Rectangle(double height, double width) { this.height = height; this.width = width; } public double getHeight() { return height; } public double getWidth() { return width; } public double getArea() { return height * width; } public double getPerimeter() { return (2 * (height + width)); } } class RectangleTest { public static void main(String[] args) { Rectangle r1 = new Rectangle(40.0, 4.0); Rectangle r2 = new Rectangle(35.9, 3.5); System.out.println("Rectangle 1:"); System.out.println("Height: " + r1.getHeight()); System.out.println("Width: " + r1.getWidth()); System.out.println("Perimeter: " + r1.getPerimeter()); System.out.println("Area: " + r1.getArea()); System.out.println(""); System.out.println("Rectangle 2:"); System.out.println("Height: " + r2.getHeight()); System.out.println("Width: " + r2.getWidth()); System.out.println("Perimeter: " + r2.getPerimeter()); System.out.println("Area: " + r2.getArea()); } }