Bohemian
Bohemian

Reputation: 6067

How do I create objects at runtime?

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

Upvotes: 4

Views: 16969

Answers (5)

Malintha
Malintha

Reputation: 4776

This is an straingth forward question and the perfect solution is using java reflection. You can create objects and cast them as need while the runtime. Also the number of object instances can be solved with this technology.

These are good references:

Reference1

Reference2

Upvotes: -1

fastcodejava
fastcodejava

Reputation: 41127

You can use array or List as shown below.

MyClass[] classes = new MyClass[n];

Then instantiate n classes with new MyClass() in a loop and assign to classes[i].

Upvotes: 0

Erkan Haspulat
Erkan Haspulat

Reputation: 12572

This would do it.

public AClass[] foo(int n){
    AClass[] arr = new AClass[n];
    for(int i=0; i<n; i++){
         arr[i] = new AClass();
    }
    return arr;
}

Upvotes: 0

Prasoon Saurav
Prasoon Saurav

Reputation: 92942

Objects in Java are only created at Runtime.

Try this:

Scanner im=new Scanner(System.in);
int n=im.nextInt();

AnyObject s[]=new AnyObject[n];
for(int i=0;i<n;++i)
{

     s[i]=new AnyObject(); // Create Object
}

Upvotes: 0

Josh Lee
Josh Lee

Reputation: 177875

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();
    }

  }
}

Upvotes: 8

Related Questions