Java Reference
In-Depth Information
Modifiers
During this week, you have learned how to define classes, methods, and variables in
Java. The techniques for programming that you learn today involve different ways of
thinking about how a class is organized. All these techniques use special modifier key-
words in the Java language.
Modifiers are keywords that you add to those definitions to change their meanings.
The Java language has a wide variety of modifiers, including the following:
Modifiers for controlling access to a class, method, or variable: public ,
protected , and private
n
The static modifier for creating class methods and variables
n
The final modifier for finalizing the implementations of classes, methods, and
variables
n
The abstract modifier for creating abstract classes and methods
n
The synchronized and volatile modifiers, which are used for threads
n
To use a modifier, you include its keyword in the definition of a class, method, or vari-
able. The modifier precedes the rest of the statement, as in the following examples:
public class Calc extends javax.swing.JApplet {
// ...
}
private boolean offline;
static final double weeks = 9.5;
protected static final int MEANING_OF_LIFE = 42;
public static void main(String[] arguments) {
// body of method
}
If you're using more than one modifier in a statement, you can place them in any order,
as long as all modifiers precede the element they are modifying. Make sure to avoid
treating a method's return type—such as void —as if it were one of the modifiers.
Modifiers are optional—as you might realize after using few of them in the preceding
five days. There are many good reasons to use them, though, as you see today.
Access Control for Methods and Variables
The modifiers that you will use the most often control access to methods and variables:
public , private , and protected . These modifiers determine which variables and meth-
ods of a class are visible to other classes.
 
Search WWH ::




Custom Search