JAVA Question Write a class named Rectangle to represent a r
JAVA Question
Write a class named Rectangle to represent a rectangle The class should have the following: 2 double data fields, width and height with default values of 1 A constructor that creates a rectangle with a given width and height A static count object that keeps track of how many rectangles are created get Area() method that returns the area a get Perimeter() method that returns the perimeter Then write a simple test class that will create 2 rectangles, one with the no-arg constructor and one passing in the width and height. Print out the perimeter and area of each rectangle, as well as the count (from the static data field)Solution
public class Rectangle {
private double width;
private double height;
private static int count = 0;
public Rectangle() {
// TODO Auto-generated constructor stub
this.width = 0;
this.height = 0;
count++;
}
/**
* @param width
* @param height
*/
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
count++;
}
public double getArea() {
return width * height;
}
public double getPerimeter() {
return 2 * (width + height);
}
/**
* @return the count
*/
public static int getCount() {
return count;
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle();
Rectangle rectangle2 = new Rectangle(4, 5);
System.out.println(\"Number of Rectangle objects Created:\"
+ Rectangle.getCount());
System.out.println(\"Area of Rectangle1:\" + rectangle1.getArea());
System.out.println(\"Perimeter of Rectangle1:\"
+ rectangle1.getPerimeter());
System.out.println(\"Area of Rectangle2:\" + rectangle2.getArea());
System.out.println(\"Perimeter of Rectangle2:\"
+ rectangle2.getPerimeter());
}
}
OUTPUT:
Number of Rectangle objects Created:2
Area of Rectangle1:0.0
Perimeter of Rectangle1:0.0
Area of Rectangle2:20.0
Perimeter of Rectangle2:18.0

