Java Reference
In-Depth Information
any attempt to assign a new value to the PI variable results in a compiler error.
Therefore final is useful to guarantee that constants are truly constant.
Constants should also be declared static ,which means there will be only
one copy for the entire class (there's no point in wasting space with multiple
copies of constants). The following class defines the constant TWO - PI :
public class MyMath {
public final static double TWO - PI = 6.28;
...
}
Then other classes can reference the constant, as in
...
double y = theta / MyMath.TWO - PI;
...
The final modifier is also used with methods to indicate that they cannot be
overridden by subclasses:
public class MyMath {
...
public final double myFormula() { ... }
}
This ensures that any subclass of MyMath does not override the myFormula()
method. It also helps to improve performance since the JVM does not need to
check for overriding versions each time the method is invoked.
5.5 Static import in J2SE 5.0
Many classes, including many in the Java core libraries, contain static constants
that are used within the class and are also useful outside the class. For exam-
ple, the java.lang.Math class contains the constants PI and E for
and e ,
respectively. As another example, we see in Chapter 7 that the BorderLayout
class contains constants such as NORTH , CENTER , etc. that are useful for laying
out graphics components.
Prior to Java version 5.0, the only way to access those constants was by fully
spelling out the names Math.PI , Math.E , BorderLayout.NORTH , etc. in
your code. With static imports, you can use just PI , E , and NORTH without all
the extra typing. To use static imports, add the static keyword to the import
statement as follows:
π
import static java.lang.Math.PI;
Then in the code body use
double area = PI * radius * radius;
Search WWH ::




Custom Search