Page 232 - Introduction to Programming with Java: A Problem Solving Approach
P. 232
198 Chapter 6 Object-Oriented Programming
data
object
methods
rest of program
Figure 6.1 To access an object’s data, you should use the object’s methods as an interface
• OOP makes it easier to develop and maintain large programs—Although switching to OOP program- ming typically makes a small program more complicated, it naturally partitions things so that the pro- gram grows gracefully and does not evolve into a giant mess. Since objects provide encapsulation, bugs (errors) and bug repairs tend to be localized.
The second bullet item needs some clarification. When an object’s data can be modified only by using
one of that object’s methods, it’s hard for a programmer to mess up an object’s data accidentally. Return-
ing again to the employee-salaries program example, assume the only way to change an employee object’s
salary is to use its adjustSalary method. Then, if there’s a bug relating to an employee’s salary, the pro-
grammer immediately knows where to look for the problem—in the adjustSalary method or in one of
the calls to the adjustSalary method.
Apago PDF Enhancer
Classes
Having discussed objects, it’s now time to talk about an intimately related entity—a class. We’ll start with a broad definition of a class, and we’ll refine it later. Broadly speaking, a class is a description of all the ob- jects it defines. As such, it is an abstraction—a concept apart from any particular instances. In Figure 6.2, note the three computers on a conveyor belt in a manufacturing plant. The three computers represent objects. The specifications document that hovers above the computers is a blueprint that describes the computers: it lists the computers’ components and describes the computers’ features. The computer-specification docu- ment represents a class. Each object is an instance of its class. Thus, for practical purposes, “object” and “instance” are synonyms.
One class can have any number of objects associated with it. A class can even have zero objects associ- ated with it. This should make sense if you think about the computer-manufacturing example. Isn’t it pos- sible to have a blueprint for a computer, but not yet have any computers manufactured from that blueprint?
We’ll now present a more complete description of a class. Above, we said that a class is a description for a set of objects. The description consists of:
a list of variables a list of methods
Classes can define two types of variables—class variables and instance variables. And classes can define two types of methods—class methods and instance methods. Chapter 5 showed you how to use the Math class’s class methods, and you have been defining a class method called main since the beginning. In Chapter 9 we’ll show you when it’s appropriate to define other class methods and define and use class variables. But it’s easy to fall into the trap of defining and using class methods and class variables improp-