Get and set methods
Introduction
We saw in the previous section that one of the principles of OO programming was the idea of encapsulation. This applies to both attributes and methods. Any important data (or methods) that we need to protect should be made private, by putting a double underscore in front of the variable name in the object. They cannot then be accessed (easily) from the main program. We then need to add a get method to our object, for a program to call if it needs to get back dome data, and a set method for the program to call, in case it needs to change an attribute.
The process for a program to read some data in an object is as follows:
The dot notation won't work, because the attribute is private. So we call the object's get method for the data. This method then goes and gets the data and returns it to the program. Setting data follows the same process.
We have modified the program we used before:
You can see that on line 14, we have the strength attribute private. We had to modify line 26 to reflect this as well. We then wrote our get method and set method, which you can see on lines 30 - 34. Finally, we added some code from line 41 onwards so we could test our changes and see the effects.
Public or private?
Attributes or methods which are completely internal to the working of an object should always be made private. There is no need for the program to access them so they should be hidden to prevent accidental changes. Set and get methods should be provided for public attributes that the program will access. It is actually possible to access private attributes without using the methods provided but this is ussally a very bad idea and should be avoided.