Java Reference
In-Depth Information
We are demonstrating the basic object-oriented principles of implementation
hiding and visibility. Wrapping attributes with accessors is but one of many
examples of information hiding. Let's now consider visibility of member func-
tions and attributes. Java has three expressed levels of visibility and one
implied level, as shown in table 9.5.
Table 9.5 Here are the visibilities supported by Java. Visibility is used to allow or deny access to
the features of a class. In this way, we can expose useful interfaces for public use, or restrict
intermediate results or useful but private features for security, safety, or design principle.
Keyword
Visibility
Usage
private
Private methods and attributes
restrict visibility to the defining
class.
Attributes and methods that compute inter-
mediate results important only to another cal-
culation. Methods that should be restricted to
the defining class for safety or security.
protected
Protected methods and
attributes restrict visibility to the
defining class plus subclasses.
Attributes and methods that may be required
for future subclasses. In general, pro-
tected should be preferred to private .
Inheritance chains may need access to many
aspects of the implementation, in ways that
are not always easy to predict.
public
Public methods do not restrict
visibility.
Only methods (not attributes) should be pub-
lic. Methods that must be exposed to fulfill
the contract for the interface are declared
with public visibility.
Unspecified
Visibility is restricted to the
package.
This visibility can be used like C++ friends.
Coordinated frameworks within a single pack-
age can use this visibility. For example, a col-
lection class utility set could use this visibility
to ensure that iterators could see other col-
lection types.
Figure 9.2 shows a conceptual view of visibility. Each widening bracket shows
expanding visibility, going from private, to protected, to public. Package
(unspecified) visibility is orthogonal, and helps to define visibility on another
axis according to the packaging of the classes, rather than the inheritance rela-
tionships specified. Visibility modifiers do not make Java's runtime behavior
more robust. Instead, through them, we can enforce policies that will help to
ensure loosely coupled interfaces, effective implementation hiding, and good
object-oriented principles.
Search WWH ::




Custom Search