Sams Teach Yourself C in 21 Days

(singke) #1
Working with Java Classes and Methods 739

BD5


Line 1 opens the class definition. By using the extendskeyword with the name
of the class ListOfNumbers, this line indicates that BetterListOfNumberswill
be a subclass of (that is, will inherit from) the class ListOfNumbers. Lines 3 to 8 define
the one new method for this class, called average. Code in this method tests the value of
the property icount. If this is greater than 0 (at least one value has been added to the
list), the average is calculated and returned. If icountis 0 (no values have been added to
the list), 0 is returned. Note that the variables icountanditotalare declared in
ListOfNumbersbut are available in BetterListOfNumbersbecause they were declared
with the protectedkeyword.
The program NumberList, shown in Listing B5.13, demonstrates these two classes.

LISTINGB5.13 NumberList.java.NumberListdemonstrates the classes ListOfNumbersand
BetterListOfNumbers
1: public class NumberList {
2:
3: public static void main(String args[]) {
4:
5: ListOfNumbers MyList = new ListOfNumbers();
6: BetterListOfNumbers MyBetterList = new BetterListOfNumbers();
7:
8: MyList.Add(4);
9: MyList.Add(8);
10: MyList.Add(9.6);
11: MyBetterList.Add(4);
12: MyBetterList.Add(8);
13: MyBetterList.Add(9.6);
14:
15: System.out.println(“From class ListOfNumbers:”);
16: System.out.print(“Total = “);
17: System.out.println(MyList.total());
18: System.out.print(“Count = “);
19: System.out.println(MyList.count());
20: System.out.println(“From class BetterListOfNumbers:”);
21: System.out.print(“Total = “);
22: System.out.println(MyBetterList.total());
23: System.out.print(“Count = “);
24: System.out.println(MyBetterList.count());
25: System.out.print(“Average = “);
26: System.out.println(MyBetterList.average());
27: }
28: }

ANALYSIS

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

Free download pdf