Question:
Consider the following class:
public class Rectangle {
private int length;
private int width;
public Rectangle(int length, int width) {
this.length = length;
this.width = width;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public void setLength(int length) {
this.length = length;
}
public void setWidth(int width) {
this.width = width;
}
public int calculateArea() {
return length * width;
}
}
Given the above class, write a program to create two Rectangle objects and perform the following operations:
Write your program in the space provided below. Include all required declarations and method calls.
Answer:
public class Main {
public static void main(String[] args) {
// Create first rectangle object
Rectangle rectangle1 = new Rectangle(5, 3);
// Create second rectangle object
Rectangle rectangle2 = new Rectangle(4, 6);
// Calculate and display area of both rectangles
System.out.println("Area of Rectangle 1: " + rectangle1.calculateArea());
System.out.println("Area of Rectangle 2: " + rectangle2.calculateArea());
// Change length of first rectangle
rectangle1.setLength(7);
// Calculate and display area of the first rectangle again
System.out.println("Area of Rectangle 1 after changing length: " + rectangle1.calculateArea());
}
}
Explanation:
The program creates two Rectangle objects using the constructor of the Rectangle class. The first object is named rectangle1
and has a length of 5 and width of 3. The second object is named rectangle2
and has a length of 4 and width of 6.
The program then calculates and displays the area of both rectangles using the calculateArea()
method of the Rectangle class. The area of rectangle1
is calculated as 5 * 3 = 15, and the area of rectangle2
is calculated as 4 * 6 = 24.
The program changes the length of rectangle1
to 7 using the setLength()
method of the Rectangle class.
Finally, the program calculates and displays the area of rectangle1
again, which is now 7 * 3 = 21.