Question:
Consider the following class definition:
public class Rectangle {
private int length;
private int width;
public Rectangle(int initialLength, int initialWidth) {
length = initialLength;
width = initialWidth;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public void setLength(int newLength) {
length = newLength;
}
public void setWidth(int newWidth) {
width = newWidth;
}
public int calculateArea() {
return length * width;
}
public int calculatePerimeter() {
return 2 * (length + width);
}
}
Create a program that demonstrates the use of the Rectangle
class.
Your program should perform the following steps:
Rectangle
objects: rect1
with a length of 4 and a width of 6, and rect2
with a length of 7 and a width of 3.rect1
using the appropriate methods.rect2
using the appropriate methods.rect1
using the calculateArea
method.rect2
using the calculateArea
method.rect1
using the calculatePerimeter
method.rect2
using the calculatePerimeter
method.Write the code for the program and provide the output.
Answer:
public class Main {
public static void main(String[] args) {
// Create two Rectangle objects
Rectangle rect1 = new Rectangle(4, 6);
Rectangle rect2 = new Rectangle(7, 3);
// Print length and width of rect1
System.out.println("Length of rect1: " + rect1.getLength());
System.out.println("Width of rect1: " + rect1.getWidth());
// Print length and width of rect2
System.out.println("Length of rect2: " + rect2.getLength());
System.out.println("Width of rect2: " + rect2.getWidth());
// Calculate and print area of rect1
int rect1Area = rect1.calculateArea();
System.out.println("Area of rect1: " + rect1Area);
// Calculate and print area of rect2
int rect2Area = rect2.calculateArea();
System.out.println("Area of rect2: " + rect2Area);
// Calculate and print perimeter of rect1
int rect1Perimeter = rect1.calculatePerimeter();
System.out.println("Perimeter of rect1: " + rect1Perimeter);
// Calculate and print perimeter of rect2
int rect2Perimeter = rect2.calculatePerimeter();
System.out.println("Perimeter of rect2: " + rect2Perimeter);
}
}
Output:
Length of rect1: 4
Width of rect1: 6
Length of rect2: 7
Width of rect2: 3
Area of rect1: 24
Area of rect2: 21
Perimeter of rect1: 20
Perimeter of rect2: 20
Explanation:
Rectangle
objects by invoking the Rectangle
constructor with the specified values for length and width.rect1
, we use the getLength()
and getWidth()
methods of the Rectangle
class on the rect1
object.rect2
by invoking the respective methods.rect1
, we call the calculateArea()
method on the rect1
object and store the result in rect1Area
variable.rect2
, we calculate the area in the same way and store it in rect2Area
variable.rect1
, we call the calculatePerimeter()
method on rect1
and store the result in rect1Perimeter
variable.rect2
in rect2Perimeter
variable.