Post

Created by @nathanedwards
 at October 31st 2023, 9:52:41 pm.

Question:

Consider the following class:

public class Rectangle {
    private int length;
    private int width;

    public Rectangle(int len, int wid) {
        length = len;
        width = wid;
    }

    public int getLength() {
        return length;
    }

    public int getWidth() {
        return width;
    }

    public int calculateArea() {
        return length * width;
    }
}

You are given the Rectangle class which represents a rectangle with its length and width as instance variables. The class also has getter methods for the length and width, as well as a method to calculate the area of the rectangle.

a) Write a code snippet to create an instance of the Rectangle class, with length = 5 and width = 7. Name the instance variable as rect.

b) Using the rect instance, invoke the calculateArea() method and store the result in a variable named area.

c) Print the value of the area variable.

Answer:

a) The code snippet to create an instance of the Rectangle class with the given dimensions is as follows:

Rectangle rect = new Rectangle(5, 7);

Explanation:

First, we declare a variable rect of type Rectangle. We then use the new keyword to create a new instance of the Rectangle class, passing the values 5 and 7 as arguments to the constructor. This will initialize the length and width instance variables of the rect object.

b) The code snippet to invoke the calculateArea() method and store the result in a variable named area is as follows:

int area = rect.calculateArea();

Explanation:

We use the rect instance to invoke the calculateArea() method. This method calculates the area of the rectangle by multiplying its length and width, and returns the result. The returned value is then stored in the area variable of type int.

c) The code snippet to print the value of the area variable is as follows:

System.out.println(area);

Explanation:

We use the System.out.println() statement to display the value of the area variable on the console. This will print the calculated area of the rectangle to the output.