Java dynamic object creation

Associate
Joined
26 Jan 2006
Posts
1,502
Hello,

I am coding a small applet and I want to create object dynamically.

lets say I got a class of animal I can create one by:

animal dog = new animal();

However, I want to create as many dogs I like (the user) through the button listeners.

How you can do this and keep track of (or set to your preference) the new object(s) name?

Thanks!
 
ArrayList myAnimals;

myAnimals.add(new animal());

like this?

edit:

got it thanx

ArrayList myAnimals = new ArrayList();
myAnimals.add(new animal());
 
Last edited:
Hi,

Another way to create objects for a dynamic name is to first get the Class for the required object, using Class.forName. Then, you can create a new instance of the class. Something like:

Code:
String myclassname = "com.animalpackage.DogClass";
Class myclass = Class.forName(myclassname);
Object myobj = myclass.newInstance();

That would give you an object of the DogClass type. There are ways of obtaining the various constructors defined on a class and using one of these to instantiate the dynamically created object too.

If you plan on doing this you might also need to do some investigation on the Java ClassLoader as there are a couple of tricky bits to watch out for.

You might also want each of your animal classes to implement a particular Interface (or extend a particular class) . For example, if DogClass and CatClass both implemented the Animal interface, then a variable of type Animal could be used to reference objects of either class (though you'd need to cast in order to get the attributes/methods particular to that class).

I haven't written many applets so don't know how much of the above would still apply. Hopefully it'll still be useful anyway.

Jim
 
Back
Top Bottom