Sams Teach Yourself C in 21 Days

(singke) #1
21: public double total() {
22: return itotal;
23: }
24: }

Lines 3 and 4 declare two variables to hold the class’s properties. Note that these
are declared with the protectedkeyword so they are not visible outside the class
except in subclasses. These properties are made available outside the class by methods.
Lines 7 to 10 are the class constructor that initializes both of the class properties to 0.
Lines 12 to 15 define the Addmethod that is called to add a value to the list. Code in this
method updates the icountanditotalproperties with the new value. Lines 17 to 19
define a method called count, which does nothing more than return the value of the
icountproperty. Lines 21 to 23 do the same thing for the itotalproperty.

738 Bonus Day 5

LISTINGB5.11 continued

ANALYSIS

This class introduces the powerful technique of making a class’s properties
private or protected, and then accessing them via class methods. This tech-
nique has many uses, including (as in this case) making a property read-only.
Because the class has a method to read the property, but none to set it, a
program that uses the class can read the value of icountanditotal, but it
cannot change these values directly.

Note


After you have written and tested the class ListOfNumbers, you realize that you need a
class that implements a similar list but has one more feature: the capability to obtain the
average of all the values that have been added to the list. Rather than rewrite the source
code for ListOfNumbers, you can simply create a subclass based on ListOfNumbers,
adding the needed functionality. The source code for this class, called
BetterListOfNumbers, is shown in Listing B5.12.

LISTINGB5.12 Better.java. The class BetterListOfNumbersis based on the
ListOfNumbersclass
1: class BetterListOfNumbers extends ListOfNumbers {
2:
3: public double average() {
4: if (icount > 0)
5: return itotal / icount;
6: else
7: return 0;
8: }
9: }

40 448201x-Bonus5 8/13/02 11:23 AM Page 738

Free download pdf