Consider the following class definition:
public class Rectangle {
private int length;
private int width;
public Rectangle(int l, int w) {
length = l;
width = w;
}
public int getLength() {
return length;
}
public int getWidth() {
return width;
}
public int calculateArea() {
return length * width;
}
}
Write a program that creates two instances of the Rectangle class. The first rectangle has a length of 5 and width of 10, while the second rectangle has a length of 8 and width of 4. Calculate and print the area of each rectangle.
You may assume that the given values for length and width are valid integers.
public class Main {
public static void main(String[] args) {
// Create first rectangle instance with length 5 and width 10
Rectangle rectangle1 = new Rectangle(5, 10);
// Create second rectangle instance with length 8 and width 4
Rectangle rectangle2 = new Rectangle(8, 4);
// Calculate and print the area of each rectangle
int area1 = rectangle1.calculateArea();
int area2 = rectangle2.calculateArea();
System.out.println("Area of rectangle 1: " + area1);
System.out.println("Area of rectangle 2: " + area2);
}
}
Explanation:
Main (or any other name).main method which serves as the entry point of the program.Rectangle constructor to initialize the rectangle1 object.Rectangle constructor to initialize the rectangle2 object.calculateArea method on rectangle1 to calculate the area of the first rectangle and store the result in the area1 variable.calculateArea method on rectangle2 to calculate the area of the second rectangle and store the result in the area2 variable.System.out.println method.