Java Reference
In-Depth Information
How It Works
Oftentimes when fields are marked as private within a class, they still need to be
made accessible to outside classes for the purpose of setting or retrieving their value.
Why not just work with the fields directly and make them public then? It is not good
programming practice to work directly with fields of other classes because by using ac-
cessors (getters) and mutators (setters), access can be granted in a controlled fashion.
By not coding directly against members of another class, you also decouple the code,
which helps to ensure that if one object changes, others that depend upon it are not ad-
versely affected. As you can see from the example in the solution to this recipe, hiding
fields and working with public methods to access those fields is fairly easy. Simply
create two methods; one is used to obtain the value of the private field, the “getter”
or accessor method. And the other is used to set the value of the private field, the
“setter” or mutator method. In the solution to this recipe, the getter is used to return the
unaltered value that is contained within the private field. Similarly, the setter is used
to set the value of the private field by accepting an argument that is of the same
data type as the private field and then setting the value of the private field to the
value of the argument.
The class that is using the getters or setters for access to the fields does not know
any details behind the methods. Furthermore, the details of these methods can be
changed without altering any code that accesses them.
Note Using getters and setters does not completely decouple code. In fact, many
people argue that using getters and setters is not a good programming practice because
of this reason. Objects that use the accessor methods still need to know the type of the
instance field they are working against. That being said, getters and setters are a stand-
ard technique for providing external access to private instance fields of an object. To
make the use of accessor methods in a more object-oriented manner, declare them with-
in interfaces and code against the interface rather than the object itself. For more in-
formation regarding interfaces, refer to recipe 5-6.
5-3. Creating a Class with a Single In-
stance
Search WWH ::




Custom Search