Reputation: 123
I need a list of all the animals. I have a basic Animal
class and would like to extend it to dogs, cats, iguanas, etc.
Is there a good way to get them all into one List
?
I want to be able to check the entire list of all animals without having to change all the previously made animals. They should know about all the other Animal
classes made after them.
Upvotes: 3
Views: 4619
Reputation: 1324
You can use List<? extends Animal> animals = new ArrayList<>();
and then add any type of animal to the list.
Upvotes: 1
Reputation: 2316
You can make any number of Animal
s by extending an Animal
base class like this:
public class Dog extends Animal {
}
Then you can declare a new list of animals.
List<Animal> animals = new ArrayList<Animal>();
Once you have done that, you can add any number of new objects the extend the Animal
class to your list.
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Iguana());
Upvotes: 3
Reputation: 21608
You can create a List<Animal>
like this:
// create empty list
List<Animal> animals = new ArrayList<>();
// add any kind of animal
animals.add(new Kangaroo());
animals.add(new Butterfly());
// use that list later
int numberOfAnimals = animals.size();
for (Animal animal : animals) {
// do something
}
Things to keep in mind:
instanceof
)extends Animal
.ArrayList
, then make your animals an ArrayList
. But in most cases defining the variable as List
or even Collection
(or Iterable
) makes your code more flexible.Upvotes: 3
Reputation: 3771
It is called Polymorphism. So basically, you answered to your question by yourself. It is perfectly legal in Java to add to collection objects of subtypes of declared collection's type.
Upvotes: 1