Java Modifiers
What is this?
The following table shows which of the ten modifiers listed in the left
column can be applied to each of the items in the other columns. For
example, it shows that you cannot have private classes or static local
variables. What it does not show is that public, private, and
protected are mutually exclusive, and that final and volatile are also
mutually exclusive.
The modifiers are keywords in the language that appear in the
declaration of a class, method, or field:
- Public items can be referenced by code in any class, private
items can be referenced only from with in the class in which they are
defined, and protected items can be referenced from only from within
the class or one of its subclasses. If none of these three modifiers
is used where one is allowed, the item has package access,
which means that it can be referenced from any class in the same
package as the one in which it is defined. (If no package is
declared, all the code in the same disk directory is part of the
"unnamed" package.)
- Static items can be referenced using the name of the class in
which they are defined to access them. They are not associated with
class instances, although they can be referenced using instance
variables.
- Final items cannot be modified. In the case of classes and
methods, it means they cannot be extended or overridden,
respectively.
- Abstract classes cannot be instantiated; abstract methods are
declared but not defined, so they cannot be called.
- Synchronized methods can be executed by only one thread at a
time.
- Transient fields are ones that will not be saved when an object
is serialized.
- Volatile fields are eliminated from certain compiler
optimizations regarding references to them.
- Native methods are implemented using a language other than Java,
usually C or C++.
An instance field is a variable that is declared outside of any method.
A local field is a variable that is declared inside a method, possibly
inside a local block inside a method.
The Table
Modifier
| Class
| Method
| Instance Field
| Local Field
|
public
| ok
| ok
| ok
| --
|
private
| --
| ok
| ok
| --
|
protected
| ok
| ok
| ok
| --
|
static
| ok
(Inner classes only)
| ok
| --
| --
|
final
| ok
| ok
| ok
| ok
|
abstract
| ok
| ok
| --
| --
|
synchronized
| --
| ok
| --
| --
|
transient
| --
| --
| ok
| --
|
volatile
| --
| --
| ok
| --
|
native
| --
| ok
| --
| --
|