Java Reference
In-Depth Information
Self-Test Exercises
1. What output is produced by the following code?
LinkedList1 list = new LinkedList1( );
list.addToStart("apple pie", 1);
list.addToStart("hot dogs", 12);
list.addToStart("mustard", 1);
list.outputList( );
2. Define a boolean valued method named is Empty that can be added to the class
LinkedList1 (Display 15.3). The method returns true if the list is empty and
false if the list has at least one node in it.
3. Define a void method named clear that can be added to the class LinkedList1
(Display 15.3). The method has no parameters and it empties the list.
PITFALL: Privacy Leaks
It may help you to understand this section if you first review the Pitfall section of the
same name in Chapter 5.
Consider the method getLink in the class Node1 (Display 15.2). It returns a value of
type Node1 . That is, it returns a reference to a Node1 . In Chapter 5, we said that if a method
(such as getLink ) returns a reference to an instance variable of a (mutable) class type, then
the private restriction on the instance variable can easily be defeated because getting a refer-
ence to an object may allow a programmer to change the private instance variables of the
object. There are a number of ways to fix this, the most straightforward of which is to make
the class Node1 a private inner class in the method Node1 , as discussed in the next subsec-
tion.
There is no danger of a privacy leak with the class Node1 when it is used in the class
definition for LinkedList1 . However, there is no way to guarantee that the class Node1
will be used only in this way unless you take some precaution, such as making the class
Node1 a private inner class in the class LinkedList1 Node1 .
An alternate solution is to place both of the classes Node1 and LinkedList1 into a
package, and change the private instance variable restriction to the package restric-
tion as discussed in Chapter 7.
Note that this privacy problem can arise in any situation in which a method returns
a reference to a private instance variable of a class type. The method getItem( ) of the
class Node1 comes very close to having this problem. In this case, the method getItem
causes no privacy leak, but only because the class String is not a mutable class (that is,
it has no methods that will allow the user to change the value of the string without
changing the reference). If instead of storing data of type String in our list we had
stored data of some mutable class type, then defining an accessor method similarly to
getItem would produce a privacy leak.
Search WWH ::




Custom Search