These
two concepts are intimately related. In real life we see classes all the time. Say you find yourself in the
supermarket looking at the fruit section, looking at a pile of apples. There are many of them, but they
all have the same or similar characteristics. Their skin is red, they are almost round, and so forth. You
can recognize them as apples, because you know the characteristics of an apple. You just identified an
object (the apple) of the class Apple (its blueprint).
A class in programming is the blueprint from which objects are created. An object is an instance of a
class; it is an individual unit capable of receiving and sending messages, processing data on its own,
and interacting with other objects.
Another example in real life are dogs; individual dogs can be thought of as objects. There are many of
them but they all belong to the class Dog.
The basic structure of a class is simple. Here we have a class Dog, enclosed in the package myAnimals.
You define a class by using the word class followed by the name you want to give it.
It is important to remember that class names always start with an uppercase letter and that every class
generally has a ???constructor,??? which is a function that shares the same name as the class. The constructor
is a function that executes by default the second you create an instance of a class (Figure 7-2).
138
CHAPTER 7
Figure 7-2. Class definition with a constructor
An object is instantiated through the use of the word new, as shown in Figure 7-3.
Pages:
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109