Java Reference
In-Depth Information
Just as you cannot cook meals in the kitchen of a blueprint, you cannot drive a car's
engineering drawings. Before you can drive a car, it must be
built
from the engineering
drawings that describe it. A completed car has an
actual
accelerator pedal to make it go
faster, but even that's not enough—the car won't accelerate on its own (hopefully!), so the
driver must
press
the pedal to accelerate the car.
Let's use our car example to introduce some key object-oriented programming concepts. Per-
forming a task in a program requires a
method
. The method houses the program statements
that actually perform its tasks. The method hides these statements from its user, just as the
accelerator pedal of a car hides from the driver the mechanisms of making the car go faster.
In Java, we create a program unit called a
class
to house the set of methods that perform the
class's tasks. For example, a class that represents a bank account might contain one method
to
deposit
money to an account, another to
withdraw
money from an account and a third to
inquire
what the account's current balance is. A class is similar in concept to a car's engineer-
ing drawings, which house the design of an accelerator pedal, steering wheel, and so on.
Just as someone has to
build a car
from its engineering drawings before you can actually
drive a car, you must
build an object
of a class before a program can perform the tasks that
the class's methods define. The process of doing this is called
instantiation
. An object is
then referred to as an
instance
of its class.
Just as a car's engineering drawings can be
reused
many times to build many cars, you can
reuse
a class many times to build many objects. Reuse of existing classes when building new
classes and programs saves time and effort. Reuse also helps you build more reliable and
effective systems, because existing classes and components often have undergone extensive
testing
,
debugging
and
performance
tuning. Just as the notion of
interchangeable parts
was
crucial to the Industrial Revolution, reusable classes are crucial to the software revolution
that has been spurred by object technology.
Software Engineering Observation 1.1
Use a building-block approach to creating your programs. Avoid reinventing the wheel—
use existing high-quality pieces wherever possible. This
software reuse
is a key benefit of
object-oriented programming.
When you drive a car, pressing its gas pedal sends a
message
to the car to perform a task—
that is, to go faster. Similarly, you
send messages
to an object
. Each message is implemented
as a
method call
that tells a method of the object to perform its task. For example, a pro-
gram might call a bank-account object's
deposit
method to increase the account's balance.
A car, besides having capabilities to accomplish tasks, also has
attributes
, such as its color,
its number of doors, the amount of gas in its tank, its current speed and its record of total