Java Reference
In-Depth Information
private: int dieValue
public: void setValue(int)
int getValue()
class interface
class Die
FIGURE 6.1: Interface of a class.
Good software design practices call for all instance variables to be defined as
private . This will hide the internal data structure of a class from the rest of the
world. As a consequence, this structure can change without the rest of the world be-
ing affected. A second advantage is that the integrity of the data is better guarded
because only the methods inside the class have access to the private data.
Figure 6.1 shows a pictorial representation of the Die class. As a general rule, all variables
should be defined as private . In other words, the variables should be hidden from the
outside world. The variables can be indirectly manipulated through the interface of the
class, that is, the class's public methods.
Note that the variable dieValue is the first variable in this topic that is defined without
using the static keyword. The reason is that the variable belongs to each object of the Die
class. In other words, every Die instance will have its own variable dieValue .Ifwecreate
100 dice, then 100 variables dieValue will be created, one for every object.
Instance variables can have a different value for every object. They are defined
without using the static keyword. Conversely, static variables are associated with
the whole class. A single instance of a static variable is created regardless of the
number of objects that are created from the class. Memory for a static variable is
created even when there are no instances (i.e., objects) of the class.
The getValue and setValue methods are called getter and setter methods, respectively.
Since the variable dieValue is private, it can be indirectly accessed through them. Once
Alfred Aho, a major contributor to the programming languages field, said during a lecture
that getter/setter methods should not be used because they circumvent the access control
rules and allow access to private variables. However, when these methods do more than just
return the value and set the value of a variable, respectively, their inclusion is warranted and
convenient. Through this textbook, we will try to avoid the use of getter/setter methods
when possible. An improved implementation of the Die class that does not provide direct
access to the private variable follows.
class Die {
private int dieValue ;
public void rollDie() {
 
Search WWH ::




Custom Search