Java Reference
In-Depth Information
which are usually public. Making the fields private has two advantages:
1. We can change the implementation of the class without requiring the user
to make changes. For example, suppose we decide to maintain the name
of an employee in two fields, the employee's last name and first name,
but still present the full name as a
String
to the user. We can do this by
changing the fields and then changing the methods appropriately. The
user would not know the difference.
2. We have control over how the field is used. For example, we can provide
only the ability to read or
get
the value of the field, but not to change it.
In general, it is the
behavior
of a class —as presented by its public meth-
ods— that is most important. Who cares how names and salaries are stored in
fields? That is not important to a user of the class. What
is
important is how they
can be obtained and how the salaries can be changed.
Later, we will see situations in which it makes sense to make fields public.
Also, a method should be private if it is used only within the class and the user
does not need to know of its existence.
Style Note
13.1, 13.1.2
method names
Getter and setter methods
Access to the value of a private field can be granted using a
getter method
,
which is a method that simply returns its value. Examples of getter methods in
class
Employee
are methods
getName
,
getStart
, and
getCompensation
.
A good naming convention for a getter method is the name of the field, cap-
italized and preceded by “
get
”. We used this convention for two getter methods.
We did not use it for field
salary
because of the way method
getCompensation
is used later in Chap. 4. The term
getSalary
will be too narrow for its use.
In the same way, we write a
setter method
for a field, in order to change its
value. Examples of setter methods in
Employee
are
setName
and
setStart
. The
parameter of the method contains the value that is to be stored in the field.
Here is a good convention for naming a setter method: use the name of the
field, capitalized and preceded by “
set
”.
3.1.2
The inside-out rule
Keyword
this
used in a method refers to the instance in which the method
appears; to reference a component named
c
(say) of that instance, we use the
notation
this
.c
. In Chap. 1, we made extensive use of keyword
this
when
referring to components of the class within the class. For example, in Chap. 1,
we would have written method
toString
of class
Employee
like this:
/** =
a representation of this instance
*/
public
String toString()
{
return this
.getName() + ",
this
.year " +
this
.getStart();
}
However, most programming languages, including Java, use a general
Search WWH ::
Custom Search