Java Reference
In-Depth Information
Private Access
To completely hide a method or variable from being used by any other classes, use the
private modifier. The only place these methods or variables can be accessed is from
within their own class.
A private instance variable, for example, can be used by methods in its own class but not
by objects of any other class. Private methods can be called by other methods in their
own class but cannot be called by any others. This restriction also affects inheritance:
Neither private variables nor private methods are inherited by subclasses.
Private variables are useful in two circumstances:
When other classes have no reason to use that variable
n
When another class could wreak havoc by changing the variable in an inappropri-
ate way
n
For example, consider a Java class called CouponMachine that generates discounts for an
Internet shopping site. A variable in that class called salesRatio could control the size
of discounts based on product sales. As you can imagine, this variable has a big impact
on the bottom line at the site. If the variable were changed by other classes, the perfor-
mance of CouponMachine would change greatly. To guard against this scenario, you can
declare the salesRatio variable as private .
The following class uses private access control:
class Logger {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
if ( (format.equals(“common”)) ! (format.equals(“combined”)) ) {
this.format = format;
}
}
}
In this code example, the format variable of the Logger class is private, so there's no
way for other classes to retrieve or set its value directly.
Instead, it's available through two public methods: getFormat() , which returns the
value of format, and setFormat( String ) , which sets its value.
The latter method contains logic that only allows the variable to be set to “common” or
“combined.” This demonstrates the benefit of using public methods as the only means of
Search WWH ::




Custom Search