In this lesson, you will learn
package ch7.l7;
class Rectangle {
int width;
int height;
// Constructor to initialize dimensions
public Rectangle(int w, int h) {
width = w;
height = h;
}
// Method to generate and return an array of Rectangle objects
public static Rectangle[] generateRectangles(int numOfRect) {
Rectangle[] rectangles = new Rectangle[numOfRect];
for (int i = 0; i < numOfRect; i++) {
// For example, create rectangles with increasing dimensions
rectangles[i] = new Rectangle(i + 1, (i + 1) * 2);
}
return rectangles;
}
}
public class RectangleArrayGenerator {
public static void main(String[] args) {
// Generate an array of 5 Rectangle objects
Rectangle[] rectangles = Rectangle.generateRectangles(5);
// Iterate over the array and print the dimensions of each rectangle
for (Rectangle rect : rectangles) {
System.out.println("Rectangle dimensions: "
+rect.width + "x" + rect.height);
}
}
}
Rectangle dimensions: 1x2
Rectangle dimensions: 2x4
Rectangle dimensions: 3x6
Rectangle dimensions: 4x8
Rectangle dimensions: 5x10
In this example, the Rectangle class contains a static method generateRectangles that takes an integer numbOfRect as its parameter.
This method initializes an array of Rectangle objects of the specified size, fills the array with Rectangle instances (in this case, with incrementing dimensions), and then returns the array.
This approach demonstrates how to encapsulate the creation of multiple instances of a class in a single method, providing a clean and efficient way to generate and work with collections of objects in Java.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.