In: Computer Science
IN JAVA PLEASE, USE COMMENTS
Following the example of Circle class, 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 specified width and height
• A method name getWidth() return the value of width
• A method named getHeight() returns value of height
• A method named setWidth(double) set the width with given value
• A method named setHeight(double) set the height with given value
• A method named getArea() that returns the area of this rectangle
• A method 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.
Here is the Java code for given question.
Output screenshot is added at the end.
Code:
Rectangle.java:
public class Rectangle {
double width,height; /*data fields*/
//no-arg constructor
public Rectangle(){
this.width=1;
this.height=1;
}
//parameterized constructor
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
//getter for width
public double getWidth() {
return width;
}
//getter for height
public double getHeight() {
return height;
}
//setter for width
public void setWidth(double width) {
this.width = width;
}
//setter for height
public void setHeight(double height) {
this.height = height;
}
//method to get area of rectangle
public double getArea(){
return this.getWidth()*this.getHeight();
}
//method to return perimeter of rectangle
public double getPerimeter(){
return this.getWidth()+this.getHeight();
}
}
Test program(RectangleDriver.java):
public class RectangleDriver {
public static void main(String[] args){
//creates a new Rectangle object
Rectangle rectangle1=new Rectangle(4,40);
//craetes a new Rectangle object
Rectangle rectangle2=new Rectangle(3.5,35.9);
//prints details of rectangle 1
System.out.println("Rectangle 1:\nWidth: "+rectangle1.getWidth()+"\nHeight: "+rectangle1.getHeight()+"\nArea: "+rectangle1.getArea()+"\nPerimeter: "+rectangle1.getPerimeter());
//prints details of rectangle 2
System.out.println("\nRectangle 2:\nWidth: "+rectangle2.getWidth()+"\nHeight: "+rectangle2.getHeight()+"\nArea: "+rectangle2.getArea()+"\nPerimeter: "+rectangle2.getPerimeter());
}
}
Output: