Java Reference
In-Depth Information
Variables
Final variables are often called constant variables (or just constants ) because they do not
change in value at any time.
With variables, the final modifier often is used with static to make the constant a class
variable. If the value never changes, you don't have much reason to give each object in
the same class its own copy of the value. They all can use the class variable with the
same functionality.
The following statements are examples of declaring constants:
public static final int TOUCHDOWN = 6;
static final String TITLE = “Captain”;
Methods
Final methods are those that can never be overridden by a subclass. You declare them
using the final modifier in the class declaration, as in the following example:
public final void getSignature() {
// body of method
}
The most common reason to declare a method final is to make the class run more effi-
ciently. Normally, when a Java runtime environment such as the java interpreter runs a
method, it checks the current class to find the method first, checks its superclass second,
and onward up the class hierarchy until the method is found. This process sacrifices
some speed in the name of flexibility and ease of development.
If a method is final , the Java compiler can put the executable bytecode of the method
directly into any program that calls the method. After all, the method won't ever change
because of a subclass that overrides it.
When you are first developing a class, you won't have much reason to use final .
However, if you need to make the class execute more quickly, you can change a few
methods into final methods to speed up the process. Doing so removes the possibility of
the method being overridden in a subclass later on, so consider this change carefully
before continuing.
6
The Java class library declares many of the commonly used methods final so that they
can be executed more quickly when utilized in programs that call them.
NOTE
Private methods are final without being declared that way because
they can't be overridden in a subclass under any circumstance.
Search WWH ::




Custom Search