Java Reference
In-Depth Information
public
and
private
Modifiers
Compare the instance variables in Displays 4.1 and 4.2. In Display 4.1, each instance
variable is prefaced with the modifier
public
. In Display 4.2, each instance variable is
prefaced with the modifier
private
. The modifier
public
means that there are no
restrictions on where the instance variable can be used. The modifier
private
means
that the instance variable cannot be accessed by name outside of the class definition.
For example, the following would produce a compiler error message if used in a program:
public
private
DateSecondTry date =
new
DateSecondTry();
date.month = "January";
date.day = 1;
date.year = 2006;
In fact, any one of the three assignments would be enough to trigger a compiler error.
This is because, as shown in Display 4.2, each of the instance variables
month
,
day
, and
year
is labeled
private
.
If, on the other hand, we had used the class
DateFirstTry
from Display 4.1 instead
of the class
DateSecondTry
in the preceding code, the code would be legal and would
compile and run with no error messages. This is because, in the definition of
Date-
FirstTry
(Display 4.1), each of the instance variables
month
,
day
, and
year
is labeled
public
.
It is considered good programming practice to make all instance variables private.
As we will explain a little later in this chapter, this is intended to simplify the task of
any programmer using the class. But before we say anything about how, on balance,
this simplifies the job of a programmer who uses the class, let's see how it complicates
the job of a programmer who uses the class.
Once you label an instance variable as
private
, there is then no way to change its value
(nor to reference the instance variable in any other way) except by using one of the meth-
ods belonging to the class. Note that even when an instance variable is private, you can still
access it through methods of the class. For the class
DateSecondTry
, you can change the
values of the instance variables with the method
readInput
, and you can obtain the
values of the instance variables with the methods whose names start with
get
. So,
the qualifier
private
does not make it impossible to access the instance variables. It
just makes it illegal to use their names, which can be a minor nuisance.
The modifiers
public
and
private
before a method definition have a similar mean-
ing. If the method is labeled
public
, there are no restrictions on its usage. If the
method is labeled
private
, the method can only be used in the definition of another
method of the same class.
Any instance variable can be labeled either
public
or
private
. Any method can be
public
or
private
. However, normal good programming practices require that
all
instance variables be private and typically most methods be public. Normally, a
method is private only if it is being used solely as a helping method in the definition of
other methods.