Following the example of the Circle class in Section 8.2, design a class named R
ID: 3775210 • Letter: F
Question
Following the example of the Circle class in Section 8.2, 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.
Write a test program that creates two Rectangle objects —one with width 4 and height 40 and the other with width 3.5 and height 35.9. Display the width, height, area, and perimeter of each rectangle in this order.
Explanation / Answer
RectangleTest.java
public class RectangleTest {
public static void main(String a[]){
Rectangle r1 = new Rectangle(4,40);
Rectangle r2 = new Rectangle(3.5,35.9);
System.out.println("Rectangle 1 details:");
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();
System.out.println("Rectangle 2 details:");
System.out.println("Width: "+r2.getWidth());
System.out.println("Height: "+r2.getHeight());
System.out.println("Area: "+r2.getArea());
System.out.println("Perimeter: "+r2.getPerimeter());
}
}
Rectangle.java
public class Rectangle {
private double width ;
private double height;
public Rectangle(){
width = 1;
height = 1;
}
public Rectangle(double w, double h){
width = w;
height = h;
}
public double getArea(){
return 2 * 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;
}
}
Output:
Rectangle 1 details:
Width: 4.0
Height: 40.0
Area: 320.0
Perimeter: 88.0
Rectangle 2 details:
Width: 3.5
Height: 35.9
Area: 251.29999999999998
Perimeter: 78.8