Defining the Data Fields, Constructors, and Core Methods

In this lesson, we will define the data fields, constructors, and the methods add, isFull, and toArray for the class BagOfStrings.

The data fields

Before we can define any of the class’s constructors and methods, we need to consider its data fields. Since the bag will hold a group of strings, one field can be an array of these strings. The length of the array defines the bag’s capacity. We can let the client specify this capacity, as well as provide a default capacity that the client can use instead. We also will want to track the current number of strings in a bag.

Thus, the following Java statements describe our data fields:

private static final int DEFAULT_CAPACITY = 25;
private String[] bag;
private int numberOfStrings;

The constructors

A constructor for this class must create the array bag. Notice that the previous declaration of the data field bag does not create an array. Forgetting to create an array in a constructor is a common mistake. To create the array, the constructor must specify the array’s length, which is the bag’s capacity. And since we are creating an empty bag, the constructor should also initialize the field numberOfStrings to zero.

The following constructor performs these steps, using a capacity given as an argument:

/** Creates an empty bag having a given capacity.
    @param capacity  The desired integer capacity. */
public BagOfStrings(int capacity)
{
   bag = new String[capacity];
   numberOfStrings = 0;
} // End constructor

Get hands-on with 1200+ tech skills courses.