Java Reference
In-Depth Information
continued
stricter and more secure coding (in fact, many of Java's built‐in classes are final
so they cannot be tampered with).
A common misconception exists that says that declaring classes or methods as
final helps to speed up execution. The explanation behind this oftentimes follows
a reasoning such as, “Well, since the compiler knows this method will never be
modified or extended by subclasses, it must be able to optimize on this.” This
perception, however, is incorrect, as the Java JIT compiler does no such thing. In
fact, declaring classes and methods final can be a great burden when program-
ming, as they limit the options for code reuse and extending functionality of exist-
ing classes. Of course, there are good reasons to declare a class or method final,
when you want to guarantee that classes and methods remain immutable (mean-
ing that they cannot be extended or modified by other classes).
For instance variables , however (as seen here), the reasoning is so dissimilar
that it's almost confusing that we use the same final keyword. Not only is set-
ting a variable to final a great way to enforce a read‐only variable, which occurs
more often than you might think (many variables are read‐only), it also does
help the compiler to optimize your program. As a final variable keeps the same
value after initialization, the compiler is able to cache (store) this value to per-
form quick checks on this variable whenever it's asked to.
variable scope
A very important aspect when working with variables in Java—and, in fact, other programming
languages as well—is their scope. Without knowing anything about variable scope, trying to access
variables can get confusing once the compiler starts yelling at you for making a mistake. Consider
the following simple class with two methods:
class ScopeTest {
void makeA() {
int a = 5;
}
void readA() {
System.out.println("The value of a is: "+a);
}
}
If you try to enter this in Eclipse, you'll get an error telling you that the variable a cannot be
resolved. The reason for this is scope. A variable's scope is basically the context in which the vari-
able is known. Depending on where a variable is declared, you will be able or unable to access this
variable. The following “levels” of scope can be defined:
Local variables: Variables that are declared inside a method or block.
Parameter variables: Variables that are declared as a method argument or a loop variable.
Instance variables: Variables that are declared in the class definition.
 
Search WWH ::




Custom Search