Java Reference
In-Depth Information
Access modifiers are the keywords public or private at the beginning of field declarations
and method signatures. For example:
// field declaration
private int numberOfSeats;
// methods
public void setAge(int replacementAge)
{ ...
}
private int computeAverage()
{ ...
}
Fields, constructors, and methods can all be either public or private, although so far we have seen
mostly private fields and public constructors and methods. We shall come back to this below.
Access modifiers define the visibility of a field, constructor, or method. If a method, for ex-
ample, is public, it can be invoked from within the same class or from any other class. Private
methods, on the other hand, can be invoked only from within the class in which they are de-
clared. They are not visible to other classes.
Concept:
Access modifiers
define the visibility
of a field, construc-
tor, or method.
Public elements are
accessible from in-
side the same class
and from other
classes; private ele-
ments are accessi-
ble only from within
the same class.
Now that we have discussed the difference between the interface and the implementation of a
class (Section 5.3.1), we can more easily understand the purpose of these keywords.
Remember: The interface of a class is the set of details that another programmer using the class
needs to see. It provides information about how to use the class. The interface includes con-
structor and method signatures and comments. It is also referred to as the public part of a class.
Its purpose is to define what the class does.
The implementation is the section of a class that defines precisely how the class works. The
method bodies, containing the Java statements, and most fields are part of the implementation.
The implementation is also referred to as the private part of a class. The user of a class does not
need to know about the implementation. In fact, there are good reasons why a user should be
prevented from knowing about the implementation (or at least from making use of this knowl-
edge). This principle is called information hiding.
The public keyword declares an element of a class (a field or method) to be part of the inter-
face (i.e., publicly visible); the private keyword declares it to be part of the implementation
(i.e., hidden from outside access).
5.11.1
Information hiding
In many object-oriented programming languages, the internals of a class—its implementation—are
hidden from other classes. There are two aspects to this. First, a programmer making use of a class
should not need to know the internals; second, a user should not be allowed to know the internals.
The first principle— need to know —has to do with abstraction and modularization as discussed
in Chapter 3. If it were necessary to know all internals of all classes we need to use, we would
never finish implementing large systems.
 
Search WWH ::




Custom Search