10.2 Setters and Getters

It is generally considered a good idea to use methods to access a class variable. Set methods are used to store a value in a variable, get methods are used to retrieve them. These methods are very easy to create, but will protect against mistakes when your classes become more complex.

For consistency, I recommend you use the following rules to write these methods:

Here’s an example of a score class with set and get methods for an integer variable called ’points’.

 
class score { 
  int points; 
 
  int  getPoints(         ) { return points ; } 
5  void setPoints(int value) { points = value; } 
}  

Another way to implement setters and getters would be to use a special symbol in the variable name. Most programmers use an underscore. This approach has the added bonus that there is a clear distinction between class variables and local variables, because all class variables start with an underscore.

 
class score { 
  int _points; 
 
  int  points(         ) { return _points ; } 
5  void points(int value) { _points = value; } 
}