Java Reference
In-Depth Information
accessing instance variables of a class—the methods can give the class control over how
the variable is accessed and the values it can take.
Using the
private
modifier is the main way that an object encapsulates itself. You can't
limit the ways in which a class is used without using
private
in many places to hide
variables and methods. Another class is free to change the variables inside a class and
call its methods in many possible ways if you don't control access.
A big advantage of privacy is that it gives you a way to change the implementation of a
class without affecting the users of that class. If you come up with a better way to
accomplish something, you can rewrite the class as long as its
public
methods take the
same arguments and return the same kinds of values.
Public Access
In some cases, you might want a method or variable in a class to be completely available
to any other class that wants to use it. For example, the
Color
class in the
java.awt
package has public variables for common colors such as
black
. This variable is used
when a graphical class wants to use the color black, so
black
should have no access con-
trol at all.
Class variables often are declared to be
public
. An example would be a set of variables
in a
Football
class that represent the number of points used in scoring. The
TOUCHDOWN
variable could equal
6
, the
FIELD_GOAL
variable could equal
3
, and so on. If these vari-
ables are public, other classes could use them in statements such as the following:
if (yard < 0) {
System.out.println(“Touchdown!”);
score = score + Football.TOUCHDOWN;
}
The
public
modifier makes a method or variable completely available to all classes. You
have used it in every application you have written so far, with a statement such as the fol-
lowing:
public static void main(String[] arguments) {
// ...
6
}
The
main()
method of an application has to be public. Otherwise, it could not be called
by a Java interpreter (such as
java
) to run the class.
Because of class inheritance, all public methods and variables of a class are inherited by
its subclasses.