Java Reference
In-Depth Information
Accessor Methods
In many cases, you may have an instance variable in a class that has strict rules for the
values it can contain. An example would be a zipCode variable. A ZIP Code in the
United States must be a number that is five digits long.
To prevent an external class from setting the zipCode variable incorrectly, you can
declare it private with a statement such as the following:
private int zipCode;
However, what if other classes must be able to set the zipCode variable for the class to
be useful? In that circumstance, you can give other classes access to a private variable by
using an accessor method inside the same class as zipCode .
An accessor method provides access to a variable that otherwise would be off-limits. By
using a method to provide access to a private variable, you can control how that variable
is used. In the ZIP Code example, the class could prevent anyone else from setting
zipCode to an incorrect value.
Often, separate accessor methods to read and write a variable are available. Reading
methods have a name beginning with get , and writing methods have a name beginning
with set , as in setZipCode( int ) and getZipCode( ).
Using methods to access instance variables is a frequently used technique in object-ori-
ented programming. This approach makes classes more reusable because it guards
against a class being used improperly.
The Java class library makes extensive use of accessor methods
that follow the same format as the getZipCode() and
setZipCode(int) examples in this section. JavaBeans, a technol-
ogy for creating Java objects whose variables can be manipulated
in an integrated development environment, also employs them.
NOTE
Static Variables and Methods
A modifier that you already have used in programs is static , which was introduced dur-
ing Day 5, “Creating Classes and Methods.” The static modifier is used to create class
methods and variables, as in the following example:
public class Circle {
public static float PI = 3.14159265F;
public float area(float r) {
return PI * r * r;
}
}
 
Search WWH ::




Custom Search