Post

Created by @nathanedwards
 at November 1st 2023, 5:03:40 pm.

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:

  1. Set the length of the first rectangle to 5 and the width to 3.
  2. Set the length of the second rectangle to 4 and the width to 6.
  3. Calculate and display the area of both rectangles.
  4. Change the length of the first rectangle to 7.
  5. Calculate and display the area of the first rectangle again.

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:

  1. 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.

  2. 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.

  3. The program changes the length of rectangle1 to 7 using the setLength() method of the Rectangle class.

  4. Finally, the program calculates and displays the area of rectangle1 again, which is now 7 * 3 = 21.