So I want to create an array of polymorphic classes in Java. It's an array of animals and I want to add different kinds of animals to the array. Animal is the super class and the different kinds of animals are sub classes and I need to implement a method that adds a specific animal to the array based on the attributes but since all kinds of animals have different attributes, I don't know how to do that. I have this basic method so far and it compiles:
public void addAnimal(String name, double weight) {
if ((numberanimals < animals.length) && (numberanimals == 0)) {
animals[0] = new Animal(name, weight);
numberanimals += 1;
} else if (numberanimals < animals.length) {
animals[numberanimals] = new Animal(name, weight);
numberanimals += 1;
} else {
System.out.println("Zoo is full.");
}
}
All animals have a name and a weight but how do I add a dog for instance based on his leash length or a shark with a boolean value that says whether he's hungry or not. Is it even possible to do that in one method like that?
Crocodile
is an Animal
.Animal
has guaranteed access to Animal
methods and public fields.Animal
is a Crocodile
using animal instanceOf Crocodile
Crocodile croco = (Crocodile)animal;
.Crocodile
to Animal[]
or to List<Animal>
as it is an Animal
.instanceOf Object
, as all classes extend Object
.Your method should be:
public void addAnimal(Animal a){
if ((numberanimals < animals.length) && (numberanimals == 0)) {
animals[0] = a;
numberanimals += 1;
} else if (numberanimals < animals.length) {
animals[numberanimals] = a;
numberanimals += 1;
} else {
System.out.println("Zoo is full.");
}
}
}
and then you can call it with any Animal
- a Lion
- addAnimal(new Lion(...));
etc.