[ANOTHER DRAFT]How To: Private Access in Classes
| QWERTYman (227) | |||
| This article assumes that you know what a class is, and how to declare one, as well as how to create an object of said class. However, something that usually confuses some beginners is how to access private class variables and functions. One way is through a public member function:
Now, the private member functions are used. If any other ways present themselves to access private access variables or functions, please add them to this article. | |||
| Faldrax (282) | |||
| The associated common question is 'Why bother with private members and methods?' As a newcomer to OO private members and methods may appear as just a way to stop you doing things - which they are, but the idea is to produce code where what it does is separated from how it does it. By making only the parts of the class that are designed to be used by other code public, and the remainder private, you are helping to make that distinction. By only providing public methods that read a private member you make it 'read only' to external code, for example. The public / private distinction may seem unimportant when just writing small pices of code for yourself, but are essential when working on larger projects with multiple developers - get into the habit from the start, and it will be easy when you need it! | |||
| mikeb570 (183) | ||||
Asked by me as a beginner.
This shows that private members are only accessed by ways you want it to. Theres no need for
TheObject.number to be public because anything I would want to do to is defined as a public method. | ||||
| Zaita (1138) | |||||
member function? It's called a Method.
To prevent the members/methods from being inherited by any potential child classes.
To prevent other programmers who are not familiar with the code from making changes through
Class.Member = X. If they assign a value to it that causes unexpected behaviour it's very difficult for you to try down this code and fix the problem. This is why encapsulation was developed. By using get/set methods you are able to put validation into the functions to ensure values assign will not cause unexpected behavior (and fall within application limits)
People often go straight to private. But you really need to consider (and will be in your design) that in a good OO application there will be quite a large child-parent hierarchy. You will end up using protected more than you would private. | |||||
| dooglio (1) | |||
| Encapsulation is also handy because the underlying member variable may change. For example, imagine in the above example the variable "number" is changed from being an intrinsic type to a class type Integer. Or perhaps a Property Bag class which allows you to store the value to disk for later retrieval. By encapsulating, the client code does not have to change. That helps down the road with maintainability. | |||
This topic is archived - New replies not allowed.
