Page 398 - Introduction to Programming with Java: A Problem Solving Approach
P. 398
364
Chapter 9 Classes with Class Members
Sample session:
Enter total number of agents: 3
Enter agent name: Bavitha
Enter agent name: Alan
Enter agent name: Rebecca
Enter Rebecca's contribution: 6000
Enter Alan's contribution: 6000
Enter Bavitha's contribution: 6000
Total value = $18,000.00
Time to Spend!
LinkedList API Class
Sun’s API library contains several classes that handle collections of data. Those classes are referred to as the collections framework or the collections API. We’ll discuss one such collection class, the ArrayList class, in depth in the next chapter. In this chapter, and this section specifically, you’ve learned about linked lists. Programmers often implement linked lists from scratch as shown in this section, but as an alterna- tive, they also implement linked lists using the LinkedList class, another class from the collections framework. To learn about the LinkedList class and all the other collection classes, see http://java.sun .com/javase/6/docs/technotes/guides/collections/.
Summary
Apago PDF Enhancer
• Class variables have a static modifier. Use class variables for attributes of the collection of all ob- jects in a class. Use instance variables for the attributes of individual objects.
• Remember that class variables have broader scope than instance variables, and instance variables have broader scope than local variables. To improve encapsulation, you should try to use variables with nar- rower scope rather than broader scope.
• An instance method can directly access class members as well as instance members.
• A class method can directly access class members, but it cannot directly access instance members. To
access a class member from a class method, you need to use a class name dot prefix.
• Use class methods for processes related to the group of all the objects in a class, for processes that must ex- ist before any objects are defined (like main), for class method helpers, and for general-purpose utilities.
• Instance constants have a final modifier only. Use them for permanent attributes of individual objects.
• Use class constants for permanent data that is not associated with any particular object. Class constants
use the final and static modifiers.
• You can use a class variable to refer to an arbitrarily long linked list of a class’s objects. This enables
another class to access all of the class’s objects through class methods only, and the other class does not need any references to specific objects.
Review Questions
§9.2 Class Variables
1. Normally, you should use the private access modifier for class variables. (T / F)
2. When should you declare a variable to be a class variable as opposed to an instance variable? 3. What are the default values for class variables?