Initializing Array size to the size that is initialized in constructor throws ArrayIndexOutOfBoundsException

35 Views Asked by At

I'm trying to create a Shelter Class, where i can shelter Animals(which is another class that has two extensions Catg,Dog) but when i initalize the shelter's size with a constructor and then initialize an array after it, it throws an exception as i mentioned. Here's the code:

Class Shelter

public class Shelter {
    String name;
    int size;

    Shelter(String name,int size){
        this.name = name;
        this.size = size;
    }
    Animal[] A = new Animal[size];
    int i = 0;
    void addAnimal(Animal animal){
        if(i < size){
            A[i] = animal;
            i++;
        }
        else{
            System.out.println("The shelter is full.");
        }
    }
    void showAnimals(){
        for (Animal animal : A) {
            if(animal == null){
                break;
            }
            System.out.println(animal);
        }
    }
}

Class Animals

public class Animal {
    String name;
    String gender;
    String colour;
    public String toString(){
        return name;
    }
    void interact(Animal anim){
        System.out.println(name + " is playing with " + anim.name);
    }
}

Main

public class Main {
    public static void main(String[] args) {
        Shelter shelter = new Shelter("Cemali",10);
        Dog dog = new Dog("Rex","Male","Brown");
        Catg catg = new Catg("Ash","Female","White");
        shelter.addAnimal(dog);
        shelter.addAnimal(catg);
        shelter.showAnimals();
    }
}

When i initialized the array without setting its size, and set its size in constructor, it worked without a problem. Why is that and how can i make it work with initializing its size outside of constructor? Here is how it looks like:

Animal[] A;
    Shelter(String name,int size){
        this.name = name;
        this.size = size;
        A = new Animal[size];
    }
0

There are 0 best solutions below