Java Reference
In-Depth Information
accessible; it is a simple enough class, with no dependencies between its fields. On
the other hand, our current implementation of the class allows a Circle object to
have a negative radius, and circles with negative radii should simply not exist. As
long as the radius is stored in a public field, however, any programmer can set the
field to any value she wants, no matter how unreasonable. The only solution is to
restrict the programmer's direct access to the field and define public methods that
provide indirect access to the field. Providing public methods to read and write a
field is not the same as making the field itself public . The crucial difference is that
methods can perform error checking.
We might, for example, want to prevent Circle objects with negative radii—these
are obviously not sensible, but our current implementation does not prohibit this.
In Example 3-4 , we show how we might change the definition of Circle to prevent
this.
m
g
O
This version of Circle declares the r field to be protected and defines accessor
methods named getRadius() and setRadius() to read and write the field value
while enforcing the restriction on negative radius values. Because the r field is pro
tected , it is directly (and more efficiently) accessible to subclasses.
Example 3-4. he Circle class using data hiding and encapsulation
package shapes ; // Specify a package for the class
public class Circle { // The class is still public
// This is a generally useful constant, so we keep it public
public static final double PI = 3.14159 ;
protected double r ; // Radius is hidden but visible to subclasses
// A method to enforce the restriction on the radius
// This is an implementation detail that may be of interest to subclasses
protected void checkRadius ( double radius ) {
if ( radius < 0.0 )
throw new IllegalArgumentException ( "radius may not be negative." );
}
// The non-default constructor
public Circle ( double r ) {
checkRadius ( r );
this . r = r ;
}
// Public data accessor methods
public double getRadius () { return r ; }
public void setRadius ( double r ) {
checkRadius ( r );
this . r = r ;
}
Search WWH ::




Custom Search