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?
There's just one significant problem preventing your code from being syntactically correct and runnable. You have misnamed the constructor in your
Lionclass. That class should be defined like this:The other issue is one of intent. As @Nickolai said, you probably don't want to be adding a specific animal inside your
AnimalListclass, but rather be adding theAnimalyou passed in, so just:To complete the picture, here's a
mainmethod that will exercise your code:This code basically answers your question. Yes, a
Lionis already anAnimal, so no type cast is needed to pass aLioninto theaddAnimalmethod, even though it accepts anAnimalas a parameter.