Java Reference
In-Depth Information
These objectives are Section 5 of the SCJP exam objectives.
The exam tests your knowledge of object-oriented (OO)
programming, including encapsulation, inheritance,
polymorphism, and good OO design that includes loose coupling
and high cohesion. This chapter covers all of these topics in detail.
Encapsulation, Coupling,
and Cohesion
The concepts of encapsulation, coupling, and cohesion are not unique to Java and represent
good design techniques in any object-oriented programming language. This section
discusses each of these design concepts in detail, starting with tight encapsulation.
Tight Encapsulation
Encapsulation refers to the combining of fi elds and methods together in a class such
that the methods operate on the data, as opposed to users of the class accessing the
fi elds directly. The term tight encapsulation refers to using encapsulation every time on
all the fi elds of a class, and only providing access to the fi elds via methods. With tight
encapsulation, no fi elds of an object can be modifi ed or accessed directly; you can only
access the fi elds through a method call.
To implement tight encapsulation, make the fi elds of a class private and provide public
accessor (“getter”) and mutator (“setter”) methods. Because a mutator or accessor method
must be invoked to access the fi elds of the object, tight encapsulation has several key benefi ts:
You can monitor and validate all changes to a field.
Similarly, you can monitor and format all access to a field.
The actual data type of a field can be hidden from the user, allowing you to change the
data type without affecting the code that uses the object, as long as you do not alter
the signatures of the corresponding accessor and mutator method.
To demon st rate , le t 's fi rst look at a class that does not implement tight encapsulation.
The following class, named Student1 , represents a student with fi elds for the year
(Freshman, Sophomore, Junior, Senior) and percentage grade of a student. The fi elds of
Student1 are public and can be accessed directly:
Search WWH ::




Custom Search