Arrays of Object

7.7 Arrays of Object

You can create arrays of objects like any other datatype. For example, in section 6.3, we created a Rectangle class to implement the basic properties of a Rectangle. The following code declares an array of five Rectangle objects:
Rectangle[] rectangles = new Rectangle[5];
The variable that references the array is named rectangles. Each element in this array is a reference variable. You must create a Rectangle object reference to array element like :
rectangles[0] = new Rectangle();
You can use a loop to create objects for each element.
array of objects
Following program demonstrates this:
/**
 * This Program creates
 * an array of rectangles.
 */
import java.util.*;

public class ArrayOfObjects
{
   public static void main(String[] args)
   {
      // Create an array to hold rectangle's data.
      Rectangle[] rectangles = new Rectangle[5];
      double length; //to hold length of rectangle
      double width;  //to hold width of rectangle

      // Create a Scanner object for keyboard input.
      Scanner console = new Scanner(System.in);
      Rectangle[] rectangles = new Rectangle[5];

      for (int i = 0; i < 5; i++)
      {
         System.out.print("Enter the length of Rectangle " + (i + 1)
                          + ": ");
         length = console.nextDouble();
         System.out.print("Enter the width of Rectangle " + (i + 1)
                          + ": ");
         width = console.nextDouble();
         rectangles[i] = new Rectangle(length, width);
         System.out.println();
      }

      for (int i = 0; i < 5; i++)
      {
         System.out.println("Area of Rectangle " + (i + 1) + ": "
                            + rectangles[i].getArea());
      }
   }
}
Output :
Enter the length of Rectangle 1: 12
Enter the width of Rectangle 1: 3
Enter the length of Rectangle 2: 5
Enter the width of Rectangle 2: 4
Enter the length of Rectangle 3: 1.5
Enter the width of Rectangle 3: 2.2
Enter the length of Rectangle 4: 6
Enter the width of Rectangle 4: 7
Enter the length of Rectangle 5: 8
Enter the width of Rectangle 5: 2
Area of Rectangle 1: 36.0
Area of Rectangle 2: 20.0
Area of Rectangle 3: 3.30
Area of Rectangle 4: 42.0
Area of Rectangle 5: 16.0

No comments:

Post a Comment

Pages