Search⌘ K
AI Features

Defining the Data Fields, Constructors, and Core Methods

Understand how to define and initialize data fields such as arrays and counters for managing strings in Java. Learn to construct objects with specified or default capacities and implement core methods like add, isFull, and toArray for effective array-based data structure management. This lesson guides you in building reliable Java classes with proper encapsulation and data handling.

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

The default constructor can invoke the previous one, passing it the default capacity as an argument, as follows:

 ...