Java Part 4: Objects and Information Hiding - The private and public declarations
(Page 4 of 5 )
Where we defined the single float variable, “value” of the Number class, we could declare it as a private member variable. This would prevent the “value” variable from being able to be modified from outside of the class, directly. The “value” variable can be seen within the class, however we will write some accessor and setter methods to manipulate the variable indirectly. This is good practice, as mentioned above:
private float value;This is the only change necessary to implement the information hiding for the “value” variable. Everything member function should be made public, so that they can be seen (and accessed) from outside of the class. If we were to make the member functions private, then any call to that function would raise an error, because it would be invisible outside of the class.
Let’s rewrite the Number class to enforce information hiding. The complete Number class is shown below, for your convenience:
// The class definition
public class Number{
// A Class member float type, set to zero by default.
private float value = 0;
// The default constructor
public Number(){}
// Another Constructor
Number( float val ){
value = val;
}
public static void main( String[] args ){
Number number = new Number();
number.addTo( 5 );
number.divideBy( 5 );
System.out.println( +number.getVal() );
System.exit(1);
}
// The Following 4 methods manipulate
public float addTo( float x ){
// the class member "value"
return value += x;
}
public float subFrom( float x ){
return value -= x;
}
public float multiplyBy( float x ){
return value *= x;
}
public float divideBy( float x ){
if( value == 0 ){
return 0;
}
return value /= x;
}
// An accessor method, simply returns the value of the "value" member
public float getVal(){
return value;
}
}There we have it. The Number class now adheres to the information hiding conventions. The Number class will now be more re-usable because the
implementation of the class may be changed without the user having to re-learn how to use it (that is, if the methods remain unchanged).
The user can still violate the rules within the class. For instance, inside the main function, the “value” variable can still be directly referenced. Anywhere outside of the class, however, this will produce an error.
Next: Conclusion >>
More Java Articles
More By Chris Noack