Aside — Constructor Chaining

  • Constructor Chaining allows a constructor to call another constructor

  • In the below example, when this(DEFAULT_CAPACITY) is called, it actually calls the constructor that takes an int

  • This then has the second constructor do the work

Note

The call to this must be first statement in the constructor body.

 1    public ContactList() {
 2        // Calls the constructor that takes an int as parameter
 3        this(DEFAULT_CAPACITY);
 4    }
 5
 6    /**
 7     * Create an empty ContactList with the array container's capacity being set to the specified size.
 8     *
 9     * @param initialCapacity Starting capacity of the fixed length array
10     */
11    public ContactList(int initialCapacity) {
12        size = 0;
13        friends = new Friend[initialCapacity];
14    }