Java Part 4: Objects and Information Hiding - Enforcing information hiding
(Page 3 of 5 )
Information hiding is a method that good programmers use to make their code more reusable. It is best to make the variables in a class invisible and use a set of visible methods to access these variables. This means that the user will not have to know how the internals of the class work, rather just how its member functions should be called.
We make member variables, such as “value” invisible so that they can’t be accessed directly by other parts of the application. Only members of the same class can access them internally. The getVal() member function was implemented to enforce this.
We also create a class like this so that the user cannot directly reference a member variable, for instance:
number.value += 3;This is a bad design habit, because the "value" variable is referenced and changed directly. A more correct approach would be:
number.addTo( 3 );This approach is more sensible, and doesn’t allow the user to directly modify the “value” variable.
Java provides formal support for information hiding. In C, there is no formal support for information hiding, and the programmer must implement setter and accessor functions to manipulate data involved with a abstract data type (an abstract data type is a collection of data, as well as the functions that operate on that data). A letdown with the C language, is that the user can circumvent these functions and access the data directly.
Next: The private and public declarations >>
More Java Articles
More By Chris Noack