In the world of objects, encapsulation is a popular term. But sometimes we never pay enough attention to properly declare the access type of instance variables. Yes, I mean to say in terms of design and class architecture perspective. The basic advantage of object oriented programming is code re-usability. Meaning, using your class in a different program or changing your class shall not affect any other parts of code, which uses it. Now, if most of your instance variables are public and if (say) several other classes extends your class, or use its objects, then if any day you want to change the behavior of that instance variables, then all those codes will require re-work. Like say, if you want to ensure that the instance variables should have a value range and it will not accept any value outside that range.
Consider a class automobile with an instance variable no_of_wheels. Will you allow any other code to assign a value of fraction or a negative value to the member variables? It is better to declare the variable as private and use getter and setter method to control the assignment behavior. Only in this way you can achieve the truest meaning of encapsulation. Here is the pseudo code example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Class Automobile { private int no_of_wheels; public setWheels(int wheel_num) { this.no_of_wheels = wheel_num; //setting value to the class variables. if(this.no_of_wheels < 0) { this.no_of_wheels = 0 - this.no_of_wheels; } } public getWheels() { return this.no_of_wheels; } } |
I know, the question in your mind is then shall I not declare any member variable as public. Sure, you can but ensure that it can have any range of values. If the type is boolean then safely, it can be a candidate of public access type. But I prefer keeping things private.
Please let me know if I am wrong.





