Sams Teach Yourself C in 21 Days

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

BD5


totally new class containing all the needed features? Not with inheritance you don’t!
Simply create a child class based on the existing class, and add a method to perform the
desired lease calculations.
To create a child class, use the extendskeyword in the class definition:
public class ChildClassNameextends ParentClassName{
...
}

Remember, you cannot inherit from a class that was created using the final
Caution keyword. Final classes cannot serve as parent classes.

Consider an example demonstrating inheritance. Suppose you have created a class called
ListOfNumbersthat keeps track of certain statistics of a list of numbers: namely, the
number of values in the list and the sum of all the values. The class also has a method
that permits you to add a number to the list. Note that the individual values in the list are
not saved, just the count and the sum. This class is called ListOfNumbers, and its code is
presented in Listing B5.11.

LISTINGB5.11 Lists.java. The class ListOfNumbersmaintains the count and total of val-
ues added to it
1: public class ListOfNumbers {
2:
3: protected int icount;
4: protected double itotal;
5:
6: //Constructor.
7: ListOfNumbers() {
8: icount = 0;
9: itotal = 0;
10: }
11:
12: public void Add(double x) {
13: icount++;
14: itotal += x;
15: }
16:
17: public int count() {
18: return icount;
19: }
20:

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

Free download pdf