Java Reference
In-Depth Information
You could include both constructors, but then you have redundant code. As we saw
in Chapter 8, you can avoid the duplication by having one constructor call the other.
The constructor that takes the capacity is the more general constructor, so you can
have the constructor that takes no arguments call it using the this(...) notation:
public ArrayIntList() {
this(100);
}
public ArrayIntList(int capacity) {
elementData = new int[capacity];
size = 0;
}
You might wonder how Java can tell the two constructors apart. The answer is that
they have different signatures. One constructor takes no arguments, whereas the second
constructor takes an integer as an argument. When Java sees the call on this(100) in
the first constructor, it knows that it is calling the second constructor because the call
includes an integer value as a parameter.
Another improvement we can make is to introduce a constant for the rather arbi-
trary value of 100 :
public static final int DEFAULT_CAPACITY = 100;
It is a good idea to make this constant public because the client might want to be
able to refer to the value to know what capacity a list has if the client doesn't specify
a specific value to use. You would then rewrite the first constructor to use the con-
stant instead of the specific value:
public ArrayIntList() {
this(DEFAULT_CAPACITY);
}
Preconditions and Postconditions
We are almost ready to put all of these pieces together into a complete class. But
before we do so, we should consider the issue of documentation. When you docu-
ment the class, you want to think in terms of important information that should be
conveyed to the client of the class. You want to describe what each method does and
you want to describe any limitations of each method. This is a great place to use pre-
conditions and postconditions, as described in Chapter 4.
Recall from Chapter 4 that preconditions are assumptions the method makes. They
are a way of describing any dependencies that the method has (“this has to be true in
order for me to do my work”). Also, recall that postconditions describe what the
method accomplishes, assuming that the preconditions are met (“I'll do this as long
as the preconditions are met”). The combination of preconditions and postconditions
is a way of describing the contract that a method has with the client.
 
Search WWH ::




Custom Search