Hi I'm really new to java and having some issues. I have a question and I'm not sure how to phrase it so I'll try to give an example.
First lets say I have three classes that share the same package. First lets say I have the following Abstract class:
public abstract class Animal {
protected String name;
protected String type;
public String getType() {
return this.type;
}
}
And the following child class
public class Lion extends Animal {
public Animal (String name, String dietType) {
this.name = name;
this.type = dietType;
}
Then lets say I have another class that keeps track of a list of animals that shares the SAME package as Lion and Animal. This class has one method that add animals into an ArrayList it possesses. The problem is when I try to create a Lion (which is a type of animal) inside the class and add it to the ArrayList of Animals it won't add.
public class AnimalList {
private ArrayList<Animal> animalList = new ArrayList<Animal>();
public void addAnimal(Animal animal) {
Lion lion1 = new Lion("Simba", "Carnivore");
animalList.add(lion1);
}
}
If I wanted to add a Lion into the ArrayList of animals how would I do so? Would I have to typecast the Lion into an Animal? But a Lion is already an Animal isn't it?