Accessors & Mutators

For data hiding to work, all attributes must be private and must never be part of the external interface.

 

Making as much of a class private as possible protects the class from unwanted changes/effects, and is essential to encapsulation. However being completely private would be useless because we need to set and get its attributes and potentially do something with them.

 

Seeing we want the protection of encapsulation, we need a mechanism that will allow us to set and get an object’s attributes, and this is achieved by the use of setter and getter methods -- or more formally: Mutators and Accessors.

 

By providing setters and getters, control of an object’s attributes still remain with the object, but allows other objects to access its attributes by sending a message to its public methods (i.e. its interface).

 

In this diagram, the setSpeed public method is used to set the speed attributes of the Motorbike object. But being able to set the speed is a bit like have a throttle and no speedo, so we need another public method to get the speed, getSpeed, and similarly for the other attributes of the object.

 

 

  • If an object wants an attribute, a method is provided to return the attribute: a getter
  • The value of the attribute is provided by invoking that getter method
  • Similarly, setters are used to set an object’s attribute value
  • The object that contains the attributes, retains control of the attribute

Leave a Reply