Question:
Consider the following class definition:
public class Rectangle {
private int width;
private int height;
// Constructor
public Rectangle(int w, int h) {
width = w;
height = h;
}
public int calculateArea() {
return width * height;
}
}
Write a code snippet to create an instance of the Rectangle
class and calculate its area using the given constructor.
Answer:
To create an instance of the Rectangle
class and calculate its area, you can use the following code:
// Create an instance of Rectangle
Rectangle rectangle = new Rectangle(5, 7);
// Calculate the area of the rectangle
int area = rectangle.calculateArea();
Explanation:
In the code snippet above, the Rectangle
class is created with a constructor that takes two parameters w
and h
. These parameters represent the width and height of the rectangle.
To create an instance of the Rectangle
class, the new
keyword is used with the constructor, passing the values 5
and 7
as arguments. This will create a new Rectangle
object with width 5
and height 7
.
Next, the calculateArea()
method is called on the rectangle
instance to calculate the area of the rectangle. The returned value is stored in the area
variable.
In this case, since the width is 5
and the height is 7
, the calculated area would be 35
.
Therefore, after executing the code snippet, the area
variable will store the value 35
.