In: Computer Science
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.
java
Program:
class Rectangle
{
double width,height;
Rectangle()
{
width=1;
height=1;
}
Rectangle(double wid, double ht)
{
setWidth(wid);
setHeight(ht);
}
void setWidth(double wid)
{
width=wid;
}
void setHeight(double ht)
{
height=ht;
}
double getWidth()
{
return width;
}
double getHeight()
{
return height;
}
double getArea()
{
return width*height;
}
double getPerimeter()
{
return(2*width + 2*height);
}
}
class TestRectangle
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(4,40);
System.out.println("\nRectangle : 1");
System.out.println("---------------------------------------------------");
System.out.println("Width: "+rect1.getWidth());
System.out.println("Height: "+rect1.getHeight());
System.out.printf("Area: %.2f\n",rect1.getArea());
System.out.printf("Perimeter:%.2f\n ",rect1.getPerimeter());
Rectangle rect2=new Rectangle(3.5,35.9);
System.out.println("\nRectangle : 2");
System.out.println("---------------------------------------------------");
System.out.println("Width: "+rect2.getWidth());
System.out.println("Height: "+rect2.getHeight());
System.out.printf("Area: %.2f\n",rect2.getArea());
System.out.printf("Perimeter:%.2f\n ",rect2.getPerimeter());
System.out.print("\n");
}
}
Output: