|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
warning (again): The Java keyword “static” means “associated with the class, not a particular instance”. It does not mean “unchanging”.
The concept of “belonging to the class-blueprint, not any particular instance” can also applies to fields, as well as methods. Most of the time, static fields are used for named-constants, so we'll discuss that first, followed by an example of a static field which isn't constant.
Named constants in other classes:
Math.PI,
Integer.MAX_VALUE,
Double.POSITIVE_INFINITY,
Double.NaN.
We can make our own named constants. As before, “static” is an adjective that we write in front of the variable-declaration.
public static double MINIMUM_WAGE = 5.15; public static double PRICE_PER_SQ_IN = 3.14; |
To do: Consider the weight-limit for explorers.
Suppose that you want all treasures, occasionally, to become temporarily weightless. (Perhaps depending on the phase of the moon.)
class Treasure { private static boolean inWeightlessPhase = false; private static void toggleWeightlessPhase() { // ...? } private _______ _______ getInWeightlessPhase { // ...? } double getWeight() { // ...? } |
Another common use of static fields is to keep track of how many times (say) the constructor has been called. This can be useful for making objects which have an ID field
class Treasure { private static int createdSoFar = 0; double weight; int id; // ... other fields omitted // constructor public Treasure( /* ... */ ) { id = createdSoFar; createdSoFar = createdSoFar + 1; // Not inside a loop! //... } } |
1 We aren't quite yet finished with how Java lets us best express named-constants; we'll see one more keyword before we're done. We started by using local-variables (because that's all we knew), improved that to fields (so that different methods could refer to the same constant), and now make it static (since named constants aren't part of a object's individual state). ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2007, Ian Barland, Radford University Last modified 2007.Aug.27 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |