Java programming course: 6.2 Example class using an array

In the previous lesson we looked at what arrays are.


Example class using an array

You will now develop a simple class that uses a single-dimensional array to model a pen that contains a group of animals.

Create a new class in virtualzoo.core called Pen as follows that declares a constant and three instance variables:

package virtualzoo.core;

public class Pen {

    public static final int CAPACITY = 10;
    
    private String name;
    private Animal[] animals;
    private int nextElementIndex;

}
 
  • The CAPACITY constant is an int that holds the maximum capacity of the pen
  • The name instance variable is a String to hold the name of the pen (e.g., "Penguin Parade")
  • The animals instance variable is declared to be an array of Animal objects, although at the moment the number of elements the array can hold has not been set
  • The nextElementIndex instance variable is a simple int whose purpose is to keep track of the next element index number. It will be used when adding a new animal to the pen

Define a constructor that initialises the name of the pen (from the argument) and number of elements the array can hold:

public Pen(String name) {
    this.name = name;
    animals = new Animal[CAPACITY];
}
 
  • The above is the equivalent of specifying animal = new Animal[10];, but using the constant is better practice since the number is liable to be required elsewhere as well, and if you ever need to change the capacity you would only need to change one line of code, that being where the constant is defined
  • The nextElementIndex variable is automatically initialised to zero so does not need to be explicitly initialised in the constructor

When a Pen object is instantiated, it contains no actual animals, just ten available elements. Therefore, define a method to add an animal to the pen:

public void add(Animal animal) {
    if (nextElementIndex < CAPACITY) {
        animals[nextElementIndex] = animal;
        nextElementIndex++;
    }
}
 
  • We have defined an add() method which requires an argument of type Animal, which means it is capable of accepting any type of animal (i.e., any subclass of Animal)
  • The if statement checks whether the next element index is less than the maximum capacity of the pen, in other words that the pen is not already full. Only if there is space will the animal be assigned to the next available slot
  • After the animal is added, the next element index variable is incremented by one ready for the next animal to be added. Note the short-cut technique used of two plus symbols after the variable name. Alternative ways of achieving the same thing would be:
nextElementIndex = nextElementIndex + 1;
nextElementIndex += 1;
 
  • If the pen is full the animal is not added and nextElementIndex is not incremented

Now define a method that returns the array:

public Animal[] getAnimals() {
    return animals;
}
 
  • Note the return type requires the square brackets to signify that you are returning an array of Animal objects rather than a single Animal object.

Client objects will find it useful to know exactly how many animals are in the pen, so define a method which returns this value:

public int getCount() {
    return nextElementIndex;
}
 

Define a setter and getter for the name attribute:

public void setName(String name) {
    this.name = name;
}
    
public String getName() {
    return name;
}
 

Finally, override toString() to return something meaningful:

@Override
public String toString() {
    return name;
}
 

Using the Pen class

To see how to use the Pen class enter the following statements into Experiments:

Pen penguinPen = new Pen("Penguin Parade");
penguinPen.add(new Penguin("Petra", Gender.FEMALE, 1));
penguinPen.add(new Penguin("Oswald", Gender.MALE, 2));

System.out.println("The pen is called " + penguinPen.getName();         
System.out.println("There are " + penguinPen.getCount() +
                " animals in the pen");
 
  • A Pen object is created, and two Penguin objects are added to the pen. Note how the penguins are instantiated directly inside the argument brackets of the add() method. You could, of course, have instantiated each penguin on a separate line assigning it to a reference variable, and then pass the variable to the add() method
  • The name and number of animals in the pen is then reported

To run the above you need to right-click the Experiments.java node in the Projects window and select Run File.

The next question is how to efficiently retrieve the individual animals in a pen, after you retrieve that array using the getAnimals() method. When you have items in an array (or other type of collection) you can iterate over them in a loop. This is the subject of the next lesson.


In the next lesson we will show how to process array items using a loop.

Next lesson 6.3: Using looping constructs with arrays


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image