Classes and Objects

We have been building DynamicArray one method at a time. Let’s pause and look at it as a whole, and use it to revisit a couple of object-oriented ideas you have likely seen before.

Here is the class so far, with the method bodies left out so we can see the fields and the methods:

public class DynamicArray {
  private int[] arr;
  private int size;

  public DynamicArray() { ... }

  public void add(int value) { ... }

  public int get(int index) { ... }

  public int size() { ... }

  private void grow() { ... }
}

Class vs. object

A class is a blueprint. DynamicArray describes what every dynamic array has (an arr and a size), what it can do (add, get, size), and how each of those behaviors is implemented (the method bodies). But the class itself is not a usable collection.

An object is an instance built from that blueprint. We create one with the new operator:

DynamicArray first = new DynamicArray();    // one object
DynamicArray second = new DynamicArray();   // a separate object

Here first and second are two distinct objects. Each has its own arr and its own size. Adding to first does not change second.

The job of the constructor, DynamicArray(), is to set up a new object so it starts in a valid state. Ours allocates the initial storage and sets size to 0.