Java Reference
In-Depth Information
modifiers. A modifier is a
Java reserved word that is used to specify particular characteristics of a program-
ming language construct. In Chapter 2 we discussed the final modifier, which is
used to declare a constant. Java has several modifiers that can be used in various
ways. Some modifiers can be used together, but some combinations are invalid.
We discuss various Java modifiers at appropriate points throughout this topic,
and all of them are summarized in Appendix E.
In Java, we accomplish object encapsulation using
Visibility Modifiers
Some of the Java modifiers are called visibility modifiers because they control
access to the members of a class. The reserved words public and private are vis-
ibility modifiers that can be applied to the variables and methods of a class. If a
member of a class has
public visibility, it can be directly referenced from outside
of the object. If a member of a class has private visibility, it can be used anywhere
inside the class definition but cannot be referenced externally. A third visibility
modifier, protected , is relevant only in the context of inheritance. We discuss it
in Chapter 9.
Public variables violate encapsulation. They allow code external
to the class in which the data is defined to reach in and access or
modify the value of the data. Therefore, instance data should be
defined with private visibility. Data that is declared as private can
be accessed only by the methods of the class.
The visibility we apply to a method depends on the purpose of that method.
Methods that provide services to the client must be declared with public visibility
so that they can be invoked by the client. These methods are sometimes referred
to as service methods. A private method cannot be invoked from outside the
class. The only purpose of a private method is to help the other methods of the
class do their job. Therefore they are sometimes referred to as
KEY CONCEPT
Instance variables should be
declared with private visibility to
promote encapsulation.
support methods.
The table in Figure 4.6 summarizes the effects of public and private visibility
on both variables and methods.
Giving constants public visibility is generally considered acceptable because,
although their values can be accessed directly, they cannot be changed because
they were declared using the final modifier. Keep in mind that encapsulation
means that data values should not be able to be
changed directly by another part
of the code. Because constants, by definition, cannot be changed, the encapsula-
tion issue is largely moot.
UML class diagrams can show the visibility of a class member by preceding it
with a particular character. A member with public visibility is preceded by a plus
sign ( + ), and a member with private visibility is preceded by a minus sign ( - ).
 
Search WWH ::




Custom Search