J2EEOnline
GofPatterns OOPortal
prev prev
  Course navigation
  Controlling access
Using access modifiers
Here is an example of access modifiers in action:
public class Circle {

  private double radius;
  private double area;

  public Circle(double radius) {
    setRadius(radius);
  }

  public double getArea() {
    return area;
  }

  public double getRadius() {
    return radius;
  }

  public void setRadius(double radius) {
    this.radius = radius;
    area = Math.PI * radius * radius;
  }

}
Assume that area represents a value that is very time consuming to calculate and that users of the Circle class access the area of a circle far more often than they set the radius. With these assumptions in mind, the Circle class has been designed so that the area of a circle will be calculated whenever the radius is set, rather than each time the getArea() method is invoked.
By using the access modifier private with the instance variables radius and area, access to these values is only available through the methods getArea(), getRadius(), and setRadius(), thus insuring that the area and radius of a circle are always consistent.
  Course navigation