I'm reading Data Structures by Koffman and Wolfgang and, in their implementation of the ArrayList, they initialize a data field outside of the constructor, and then give it a different value in the constructor.

public class KWArrayList {
    private static final int INITIAL_CAPACITY = 10;
    private int capacity = 0;

    public KWArrayList() {
        capacity = INITIAL_CAPACITY;
    }
}

Why do they initialize capacity to 0 outside of the constructor and then give it a different value in the constructor?

1

There are 1 answers

1
Basil Bourque On BEST ANSWER

In this particular example, there is no point in defaulting to zero when the one and only constructor sets the value to the constant of ten. No harm is done, but no benefit either.

As others commented, there is likely more to come in your textbook, evolving this class and subclasses to a point where having a default of zero makes sense.

However… defaulting to a value of specifically zero is especially pointless since a primitive int automatically defaults to zero. One possible benefit is for the authoring programming to make explicitly clear to any reading programmers that zero is indeed their intended default.