My goal is this: Be able to save an array of objects (in this case; Animal
) to disc. Then I would like to be able to load them. I have used JSON to do this, but left it out in this snippet for clarity. I would like to be able to make many more classes of Animal
that will have many more fields (see Unicorn
Class
below).
The class of the object cannot be known in advance. How can I get addAnimal
to work using a String
input?
AnimalWrangler aw;
void setup()
{
aw = new AnimalWrangler();
aw.addAnimal("cat");
aw.addAnimal("horse");
aw.addAnimal("unicorn");
aw.addAnimal("unknown");
}
class AnimalWrangler
{
ArrayList<Animal> animals;
AnimalWrangler()
{
animals = new ArrayList<Animal>();
}
void addAnimal(String type)
{
//makes an animal according to type
///if type does not exist then throw
//add to animals array
}
}
class Animal
{
String type;
Animal()
{
}
}
class Cat extends Animal
{
Animal animal;
Cat()
{
animal = new Animal();
type = "cat";
}
}
class Horse extends Animal
{
Animal animal;
Horse()
{
animal = new Animal();
type = "horse";
}
}
class Unicorn extends Animal
{
Animal animal;
float magic_level;
/////classes can have any number of attributes
Unicorn()
{
animal = new Animal();
type = "unicorn";
}
}