In: Computer Science
PUT IN JAVA PROGRAMMING LANGUAGE
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.
Explanation:I have written both the classes Rectangle and Client.I have implemented all the methods and attributes as mentioned in the question.I have also shown the output, please find the image attached with the answer.Please upvote if you liked my answer and comment if you need any modification or explanation.
//Rectangle class
public class Rectangle {
double width;
double height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(double width, double height)
{
this.width = width;
this.height = height;
}
public double findArea() {
return width * height;
}
public double findPerimeter() {
return (2 * width + 2 *
height);
}
}
//Client class
public class Client {
public static void main(String[] args) {
Rectangle rectangle1 = new
Rectangle(12.5, 7.5);
System.out
.println("The area of rectangle 1 is " +
rectangle1.findArea());
System.out.println("The perimeter
of rectangle 1 is "
+ rectangle1.findPerimeter());
Rectangle rectangle2 = new
Rectangle(5, 7);
System.out
.println("The area of rectangle 2 is " +
rectangle2.findArea());
System.out.println("The perimeter
of rectangle 2 is "
+ rectangle2.findPerimeter());
}
}
Output: