Search code examples
javainheritancepolymorphismsubclasssuperclass

Is it possible to have alternating conditions in a method in Java?


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?


Solution

    1. Each Crocodile is an Animal.
    2. Animal has guaranteed access to Animal methods and public fields.
    3. You can check if an Animal is a Crocodile using animal instanceOf Crocodile
    4. If it is a Crocodile, you can cast: Crocodile croco = (Crocodile)animal;.
    5. You can add Crocodile to Animal[] or to List<Animal> as it is an Animal.
    6. Every object is an 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.