Sams Teach Yourself C in 21 Days

(singke) #1
From class ListOfNumbers:
Total = 21.6
Count = 3
From class BetterListOfNumbers:
Total = 21.6
Count = 3
Average = 7.2
Line 5 declares a variable of type ListOfNumbersand also uses the newkeyword
to create a new instance of the class. Line 6 does the same for the class
BetterListOfNumbers. Lines 8 to 10 use the addmethod to add three values to the
ListOfNumbersobject. Lines 11 to 13 add the same three values to the
BetterListOfNumbersobject. The remaining code displays the property values from the
two objects. As you can see, the BetterListOfNumbersobject has all the properties and
methods of its parent class, as well as its own additional method,average.

Summary ............................................................................................................


Classes are at the heart of Java programming, and today you have learned the fundamen-
tals of creating and using classes in a Java program. A class is an independent software
component that can have properties (which hold data) and methods (which perform
actions). You saw that Java classes you create will be placed in a package with related
classes. You also learned that a Java file must use the importkeyword in order to use
classes that are not a part of its project. Finally, you saw how the very powerful, object-
oriented technique of inheritance is used, permitting a new class to be created based on
an existing class.

Q&A ....................................................................................................................


Q How is a Java class that is a stand alone program different from a class that is
not itself a program?
ATo be a program, a class must include a mainmethod. This is where execution
starts when the program runs. Other classes do not have main.
Q What are the two main components that make up Java classes?
AOne major component of Java classes is properties. A class property is used to
store data. The other main component is the method. A method contains code that
performs some action.
Q When you overload a method, the methods have the same name. How does
Java tell overloaded methods apart?

740 Bonus Day 5

OUTPUT

ANALYSIS

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

Free download pdf