(The Rectangle class) (WOULD APPRECIATE IT IF THE
PROGRAM/ANSWER COULD BE DIRECTLY COPY AND PASTED, also this should
be in java)
Following the example of the Circle class in Section 9.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.
Draw the UML diagram for the class and then implement the
class.
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.
Sample Run
The area of a rectangle with width 4.0 and height 40.0 is
160.0
The perimeter of a rectangle is 88.0
The area of a rectangle with width 3.5 and height 35.9 is
125.64999999999999
The perimeter of a rectangle is 78.8
Class Name: Exercise09_01
import java.util.*;
//class Rectangle
class Rectangle
{
//data fields
private double width,height;
//no-arg constructor
public Rectangle()
{
this.width = 1;
this.height = 1;
}
//argument constructor
public Rectangle(double w,double h)
{
this.width = w;
this.height = h;
}
//get width
public double getWidth()
{
return width;
}
//get height
public double getHeight()
{
return height;
}
//function to calculate area
double getArea()
{
double area = width*height;
return area;
}
//function to calculate perimeter
double getPerimeter()
{
double perimeter = 2*(height+width);
return perimeter;
}
}
//driver code
class Main {
public static void main(String[] args) {
//created object of class Rectangle rec1
Rectangle rec1 = new Rectangle(4,40);
double area = rec1.getArea();
double perimeter = rec1.getPerimeter();
System.out.println("The area of a rectangle with width "+rec1.getWidth()+" and height "+rec1.getHeight()+" is "+area);
System.out.println("The perimeter of rectangle is "+perimeter);
//created object of class Rectangle rec2
Rectangle rec2 = new Rectangle(3.5,35.9);
double area1 = rec2.getArea();
double perimeter1 = rec2.getPerimeter();
System.out.println("The area of a rectangle with width "+rec2.getWidth()+" and height "+rec2.getHeight()+" is "+area1);
System.out.println("The perimeter of rectangle is "+perimeter1);
}
}
Output::
Note:: If any queries please comment.
Get Answers For Free
Most questions answered within 1 hours.