javaabstract-classparent-childaddchild

Trouble with Abstract classes and their children in Java. Really confused


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?


Solution

  • There's just one significant problem preventing your code from being syntactically correct and runnable. You have misnamed the constructor in your Lion class. That class should be defined like this:

    public class Lion extends Animal {
        
        public Lion (String name, String dietType) {
            this.name = name;
            this.type = dietType;
    
    }
    

    The other issue is one of intent. As @Nickolai said, you probably don't want to be adding a specific animal inside your AnimalList class, but rather be adding the Animal you passed in, so just:

    public class AnimalList {
        private ArrayList<Animal> animalList = new ArrayList<Animal>();
    
        public void addAnimal(Animal animal) {
            animalList.add(animal);
        }
    }
    

    To complete the picture, here's a main method that will exercise your code:

    public static void main(String[] args) {
        AnimalList al = new AnimalList();
        Lion lion1 = new Lion("Simba", "Carnivore");
        al.addAnimal(lion1);
    }
    

    This code basically answers your question. Yes, a Lion is already an Animal, so no type cast is needed to pass a Lion into the addAnimal method, even though it accepts an Animal as a parameter.