Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create objects at runtime?

Tags:

java

arrays

I need to make a number of distinct objects of a class at runtime. This number is also determined at runtime.

Something like if we get int no_o_objects=10 at runtime. Then I need to instantiate a class for 10 times.
Thanks

like image 347
Bohemian Avatar asked Feb 27 '23 21:02

Bohemian


1 Answers

Read about Arrays in the Java Tutorial.

class Spam {
  public static void main(String[] args) {

    int n = Integer.valueOf(args[0]);

    // Declare an array:
    Foo[] myArray;

    // Create an array:
    myArray = new Foo[n];

    // Foo[0] through Foo[n - 1] are now references to Foo objects, initially null.

    // Populate the array:
    for (int i = 0; i < n; i++) {
      myArray[i] = new Foo();
    }

  }
}
like image 126
Josh Lee Avatar answered Mar 05 '23 19:03

Josh Lee