Page 394 - Introduction to Programming with Java: A Problem Solving Approach
P. 394
360 Chapter 9 Classes with Class Members
FundRaiser
+GOAL : double = 10000.0
+main(args : String[]) : void
Agent
-listOfAgents : Agent -NAME : String
-value : double = 0.0 -nextAgent : Agent
+Agent(name : String) -getValue() : double -addValue() : void +getAllValues() : double +addAllValues() : void
Figure 9.7 UML class diagram for driver of FundRaiser program
provide the only access route to everything else in this class. Do you remember the rule that a class method cannot access an instance member directly? If that rule is valid, and everything else is some kind of in- stance member, how can these two class methods access everything else? These methods do not access any instance members directly. They directly access the class variable listOfAgents. That class variable gives them a reference to an object, and each object gives them the reference to the next object. These object references enable the class members to access everything indirectly.
It’s time to look at the implementation code. Figure 9.8 shows the FundRaiser driver class. The
driver prompts the user to enter a desired number of agents, and the for loop steps through a process that
inputs each agent’s name and instantiates an Agent object with that name. The subsequent do loop initi- Apago PDF Enhancer
ates each fund-raising campaign by calling the addAllValues method. Then it determines the result of that campaign by calling the getAllValues method. Then it prints the cumulative result after that campaign. If the result is still less than GOAL, it launches another campaign until the goal is attained. Notice that this driver contains no references to particular Agent objects. It does not even contain a reference to the linked list of agents. All access to data in the Agent class is controlled by the Agent class methods, addAllValues and getAllValues. The data is well encapsulated—a very good thing indeed!
Figure 9.9a shows the first part of the Agent class. The class variable, listOfAgents, initially con- tains null, because initially there are no objects in the list. Now look at the constructor. The first instan- tiation assigns this null value to the first object’s nextAgent reference variable. Then it uses the this reference to assign the first object to the listOfAgents class variable. The second instantiation assigns the reference now in the listOfAgents reference variable (a reference to the first object) to the second object’s nextAgent instance reference variable. Then it uses the this reference to assign the second ob- ject to the listOfAgents class variable. Thus, the list of linked objects builds up like this:
after first instantiation:
after second instantiation:
listOfAgents
<First object> nextAgent
null
listOfAgents
<Second object> nextAgent
<First object> nextAgent
null