Java Reference
In-Depth Information
5-2. Making Private Fields Accessible To
Other Classes
Problem
You would like to create
private
instance members so that outside classes cannot
access them directly. However, you would also like to make those
private
members
accessible via a controlled method.
Solution
Encapsulate the
private
fields by making getters and setters to access them. The fol-
lowing code demonstrates the declaration of a
private
field, followed by accessor
(getter) and mutator (setter) methods that can be used to obtain or set the value of that
field from an outside class:
private String firstName = null;
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
The
getFirstName()
method can be used by an outside class to obtain the
value of the
firstName
field. Likewise, the
setFirstName(String
firstName)
method can be used by an outside class to set the value of the
firstName
field.