Java Reference
In-Depth Information
10.7
What is wrong in the following code?
public class
Test {
private int
id;
public void
m1() {
this
.id =
45
;
}
public void
m2() {
Test.id =
45
;
}
}
Class abstraction
is the separation of class implementation from the use of a class. The
details of implementation are encapsulated and hidden from the user. This is known as
class encapsulation
.
Key
Point
In Chapter 5, you learned about method abstraction and used it in stepwise refinement. Java
provides many levels of abstraction, and
class abstraction
separates class implementation
from how the class is used. The creator of a class describes the functions of the class and lets
the user know how the class can be used. The collection of methods and fields that are acces-
sible from outside the class, together with the description of how these members are expected
to behave, serves as the
class's contract
. As shown in Figure 10.3, the user of the class does
not need to know how the class is implemented. The details of implementation are encapsu-
lated and hidden from the user. This is called
class encapsulation
. For example, you can cre-
ate a
Circle
object and find the area of the circle without knowing how the area is computed.
For this reason, a class is also known as an
abstract data type
(ADT).
class abstraction
class's contract
class encapsulation
abstract data type
Class implementation
is like a black box
hidden from the clients
Class Contract
(signatures of
public methods and
public constants)
Clients use the
class through the
contract of the class
Class
F
IGURE
10.3
Class abstraction separates class implementation from the use of the class.
Class abstraction and encapsulation are two sides of the same coin. Many real-life exam-
ples illustrate the concept of class abstraction. Consider, for instance, building a computer
system. Your personal computer has many components—a CPU, memory, disk, motherboard,
fan, and so on. Each component can be viewed as an object that has properties and methods.
To get the components to work together, you need know only how each component is used
and how it interacts with the others. You don't need to know how the components work inter-
nally. The internal implementation is encapsulated and hidden from you. You can build a
computer without knowing how a component is implemented.
The computer-system analogy precisely mirrors the object-oriented approach. Each com-
ponent can be viewed as an object of the class for the component. For example, you might
have a class that models all kinds of fans for use in a computer, with properties such as fan
size and speed and methods such as start and stop. A specific fan is an instance of this class
with specific property values.
As another example, consider getting a loan. A specific loan can be viewed as an object of
a
Loan
class. The interest rate, loan amount, and loan period are its data properties, and