By Tony Bevis on Wednesday, 11 October 2023
Category: Java

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:


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

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:

Now define a method that returns the array:


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

Define a setter and getter for the name attribute:

Finally, override toString() to return something meaningful:

Using the Pen class

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

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

Related Posts

Leave Comments