Java Reference
In-Depth Information
Thinking about Encapsulation
When we declared the fields for ArrayIntList , we followed the usual convention of
declaring them to be private. This can cause a problem for a client of the class.
Suppose that the client has made a series of calls on the add method and wants to
know how many elements are in the list. For example, the client might want to write
code like the following:
Scanner input = new Scanner(new File("data.txt"));
ArrayIntList list = new ArrayIntList();
while (input.hasNextInt()) {
list.add(input.nextInt());
}
System.out.println(list);
// report the size of the list, but how?
The information the client wants is stored internally in the field called size . But
because the field is declared to be private, the client can't access the value.
There are several clumsy ways to solve this problem. One solution would be to
change the field from private to public, but as we saw in Chapter 8, making the field
public breaks encapsulation and leaves the list object open to unwanted modifica-
tions. It's not a problem to allow the client to examine the value of the field, but sup-
pose the client tried to set it to an illegal value, as in the following two examples:
list.size = -38;
list.size = 5000;
Allowing the client to reach into the object opens the door for the client to put the
object into a bad state.
Another solution would be to force the client to keep track of the size, but that is a
rather silly solution. Why should both the object and the client keep track of this
information? It puts an undue burden on the client and it leads to unnecessary dupli-
cation of effort.
The right solution is to keep the field private, but to introduce an accessor method
that allows the client to examine the value of the size field:
public int size() {
return size;
}
Then the client can write code like the following:
System.out.println("size = " + list.size());
This line of code looks fairly similar to code that accesses the field directly. The dif-
ference here is that we are calling a method called size . The method allows the client
to examine the field without giving the client the ability to change the value of the field.
 
Search WWH ::




Custom Search