In: Computer Science
PUT IN JAVA PROGRAMMING
The Rectangle 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 a rectangle. The default values are 1 for both
width and height.
• A no-arg (default) constructor that creates a default
rectangle.
• A constructor that creates a rectangle with the specified width
and height.
• A method named findArea() that finds the area of this
rectangle.
• A method named findPerimeter() that finds the perimeter of this
rectangle.
• Create a client (test) class (program) to test and use your
Rectangle class. In the client program, you need to create objects
of the Rectangle type and use those objects to perform some
meaningful and valid rectangle operations (finding area and
perimeter). The test/client class should display all results
public class Rectangle
{
/**Instance variables */
double width ;
double height;
/*Name of the constructor must match with
* the name of the class, Rectangle*/
public Rectangle()
{
width=1;
height=1;
}
/*Name of the constructor must match with
* the name of the class, Rectangle*/
public Rectangle(double newWidth, double newHeight)
{
width = newWidth;
height = newHeight;
}
/**Returns area */
public double FindArea()
{
return width * height;
}
/**Returns perimeter */
public double FindPerimeter()
{
return 2*(width + height);
}
}/**End of Rectangle class*/
Create another file named client.java
import java.text.DecimalFormat;
public class client
{
public static void main (String[] args)
{
Rectangle rectangle = new Rectangle(4,40);
/**Create an instace of DecimalFormat class*/
DecimalFormat df=new DecimalFormat("#,##.##");
System.out.println("The details of the given rectangle");
System.out.println("Width of Rectangle:" + rectangle.width);
System.out.println("Height of Rectangle:" + rectangle.height);
System.out.println("Area of Rectangle:" + df.format(rectangle.FindArea()));
System.out.println("Perimeter of Rectangle:"+ rectangle.FindPerimeter());
System.out.println();
}
}
Output: