CS11 – Advanced Java Winter 2011-2012 Lecture 3Java Constants n Frequently need to define constants in Java code public class BoggleBoard { /** Default size for a Boggle board. */ public static final int DEFAULT_SIZE = 4; ... } n Standard conventions for Java constants: q Name usually follows ALL_CAPS naming convention q Declare public static final q (or, use private / protected if appropriate)The static Keyword n Members of a class can be declared static q They are associated with the class, not a particular object q For static fields, there is only one copy of the value n Example: public class CommandPrompt { public static final String PROMPT = "Type command: "; ... } q PROMPT is an object, but it isn’t associated with individual CommandPrompt instances q Only one value, and all code can share that single value q Much more efficient memory usage than an instance field, when other code can share a single valueStatic Initialization n When are static fields initialized? public class CommandPrompt { public static final String PROMPT = "Type command: "; ... } n The VM initializes a class the first time the type is actually used by other code. q Class definition is found via the classpath, and then verified n e.g. all instructions are valid; jump instructions go to valid addresses; etc. q Any references to other types may be verified and resolved n (may involve the loading of additional classes, of course) q Finally, static fields in the class are initializedStatic Initialization (2) n Static fields are initialized at the end of the class-load process n Sometimes, can’t initialize a static field with a single line of code public class NoiseGenerator { public static final Vector3f[] noiseVectors = new Vector3f[1024]; ... } q Also need to initialize the noise-vector elements to random unit-vectors q Clearly can’t do it in a single line! n How to implement this static initialization?Static Initialization (3) n Classes can specify static initializers: public class NoiseGenerator { public static final Vector3f[] noiseVectors = new Vector3f[1024]; static { for (int i = 0; i < noiseVectors.length; i++) { noiseVectors[i] = new Vector3f(); ... // Initialize the vector } } ... } q Static initializers cannot throw checked exceptions! q Initialization of static fields, and execution of static initializers, occurs in order of appearance in the source file q Static initialization is also specified to be thread-safe in JavaThe final Keyword n Java variables can be declared as final q The variable can only be assigned to once. n Frequently used for constant class and instance fields public class CommandPrompt { public static final String PROMPT = "Type command: "; ... } q PROMPT can only be written to once, and then it is fixed n final fields are usually assigned where they are declared, but this is not strictly required by Java! q final instance fields must be assigned to, by the end of every constructor q final class fields must be assigned to, by some static initializerThe final Keyword (2) n final sometimes uses on local variables or method-arguments q Prevents reassignment to variables that shouldn’t change q Used to reduce correctness issues q Technique does have some limited usefulness… J n Example: int findWord(String w, final ArrayList<String> words) { int i = 0; for (String s : words) { if (s.equals(w)) return i; i++; } return -1; } n What can’t we do with words? q We can’t set words to refer to something else q Increases the correctness of our own method (slightly)The final Keyword (3) n Example: int findWord(String w, final ArrayList<String> words) { int i = 0; for (String s : words) { if (s.equals(w)) return i; i++; } return -1; } n What can we do with words? q We can call any of the methods on words… q We can call mutators on words! n words.add("yo' mama!"); n words.clear(); n final only prohibits reassignment to the variable n Declaring words as final doesn’t really get us much…final and const n Java final keyword is nothing like C++ const q (and Java has no equivalent to C++ const) n You will probably run into projects that use final for method-args and local variables… q Just be aware of the significant limitations of this technique n If you really need immutable state: q Create a class without mutators! n (and if necessary, a subclass that provides mutators) n Java String, Integer, etc. classes are all immutable q Or, see Collections.unmodifiableList(List), etc. n Provides an immutable view of another collection n Original collection is still mutable, but can pass the immutable view to other methods to work withBack to Java Constants… n Covered the standard modifiers used for constants public class BoggleBoard { /** Default size for a Boggle board. **/ public static final int DEFAULT_SIZE = 4; ... } n For simple constants, this is the recommended way q When constant is an object, improves memory efficiency n Two other common ways constants are often used q Both are not so good. JInterfaces and Constants n Interfaces can contain two kinds of members q Public methods, and constants! n Constants are declared as static final, since all interface members are automatically public n When a package uses a lot of constants, commonly put into a “constant interface” q The interface contains only constants, no methods n Lots of examples of this in the Java API q javax.swing.SwingConstants interface n e.g. defines alignment constants LEFT, CENTER, RIGHT q Many Swing classes “implement” SwingConstants, so they can easily use the constants in their implementations n No methods need to be added; SwingConstants has none!Joshua Bloch and Constant Interfaces n Interfaces define a type in Java q They specify a set of behaviors that implementing objects provide n When a class implements an
View Full Document