Java Reference
In-Depth Information
4.2
Information Hiding and Encapsulation
We all know—the
Times
knows—but we pretend we don't.
VIRGINIA WOOLF,
Monday or Tuesday
information
hiding
Information hiding
means that you separate the description of how to use a
class from the implementation details, such as how the class methods are defined.
You do this so that a programmer who uses the class does not need to know the
implementation details of the class definition. The programmer who uses the class can
consider the implementation details as hidden, since he or she does not need to look
at them. Information hiding is a way of avoiding information overloading. It keeps
the information needed by a programmer using the class within reasonable bounds.
Another term for information hiding is
abstraction
. The use of the term
abstraction
for information hiding makes sense if you think about it a bit. When you abstract
something, you are discarding some of the details.
Encapsulation
means grouping software into a unit in such a way that it is easy to
use because there is a well-defined simple interface. So, encapsulation and information
hiding are two sides of the same coin.
Java has a way of officially hiding details of a class definition. To hide details, mark
them as
private
, a concept we discuss next.
abstraction
encapsulation
Encapsulation
Encapsulation
means that the data and the actions are combined into a single item (in
our case, a class object) and that the details of the implementation are hidden. The terms
information hiding
and
encapsulation
deal with the same general principle: If a class is
well designed, a programmer who uses a class need not know all the details of the
implementation of the class but need only know a much simpler description of how to use
the class.
VideoNote
Information
Hiding
Example
API
The term
API
stands for
application programming interface
. The API for a class is a
description of how to use the class. If your class is well designed, using the encapsulation
techniques we discuss in this topic, then a programmer who uses your class need only read
the API and need not look at the details of your code for the class definition.
ADT
The term
ADT
is short for
abstract data type
. An ADT is a data type that is written using
good information hiding techniques.