Java Reference
In-Depth Information
Data Hiding and Encapsulation
We started this chapter by describing a class as a collection of data and methods.
One of the most important object-oriented techniques we haven't discussed so far is
hiding the data within the class and making it available only through the methods.
This technique is known as encapsulation because it seals the data (and internal
methods) safely inside the “capsule” of the class, where it can be accessed only by
trusted users (i.e., the methods of the class).
Why would you want to do this? The most important reason is to hide the internal
implementation details of your class. If you prevent programmers from relying on
those details, you can safely modify the implementation without worrying that you
will break existing code that uses the class.
m
g
O
You should always encapsulate your code. It is almost always
impossible to reason through and ensure the correctness of
code that hasn't been well-encapsulated, especially in multi‐
threaded environments (and essentially all Java programs are
multithreaded).
Another reason for encapsulation is to protect your class against accidental or will‐
ful stupidity. A class often contains a number of interdependent fields that must be
in a consistent state. If you allow a programmer (including yourself ) to manipulate
those fields directly, he may change one field without changing important related
fields, leaving the class in an inconsistent state. If instead he has to call a method to
change the field, that method can be sure to do everything necessary to keep the
state consistent. Similarly, if a class defines certain methods for internal use only,
hiding these methods prevents users of the class from calling them.
Here's another way to think about encapsulation: when all the data for a class is hid‐
den, the methods define the only possible operations that can be performed on
objects of that class.
Once you have carefully tested and debugged your methods, you can be confident
that the class will work as expected. On the other hand, if all the fields of the class
can be directly manipulated, the number of possibilities you have to test becomes
unmanageable.
This idea can be carried to a very powerful conclusion, as we
will see in “Safe Java Programming” on page 195 when we dis‐
cuss the safety of Java programs (which differs from the con‐
cept of type safety of the Java programming language).
Other, secondary, reasons to hide fields and methods of a class include:
Search WWH ::




Custom Search