RU beehive logo ITEC dept promo banner
ITEC 120
2007fall
ibarland,
jdymacek

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs

lect10a
static fields

Reminder: static methods

(You can check your answers.)
warning (again): The Java keyword “static” means “associated with the class, not a particular instance”. It does not mean “unchanging”.

static fields

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 revisited1

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;
Other people then use these by writing the “classname-dot” (not “object-dot”): if (newSalary < PizzaServer.MINIMUM_WAGE) ....

To do: Consider the default value for the image-URL, in Treasures. We don't need every single Treasure carrying around its own copy of UNKNOWN_IMAGE_URL. How do we make that field static.

To do: Consider the weight-limit for explorers.

  1. If we decided we wanted this amount to be a named constant, how would we declare and initialize it? In which class? How would we use it? See solution
  2. Advantage: Like any named amount, using a field both makes it clear what that number in the code means (not a magic number!). And it lets us change that weight-limit in one place, rather than in many, should .
    As far as the design of our program, is the weight-limit better to have as a static field, or a regular field? Should this field be public, or private? See solution

Non-constant static fields: a weightless phase

Suppose that you want all treasures, occasionally, to become temporarily weightless. (Perhaps depending on the phase of the moon.)
Hint: Don't try to go and change the weight field of every single Treasure that has ever been created. (We don't even know how we could do that yet.) Instead, always keep the same weight field inside a Treasure, but when that Treasure is asked its weight, it first checks whether it's currently in a weightless phase and in that situation answers 0 instead of the value stored in the field.

class Treasure {
  private static boolean inWeightlessPhase = false;

  /** Flip ("toggle") the status of whether or not we're in a weightless phase.
   *  (This method plays the role of a setter, in a way.)
   */
  private static void toggleWeightlessPhase() {
    // ...?
    }

  /** Return whether or not we're currently in a weightless phase.
   * @return whether or not we're currently in a weightless phase.
   */
  private _______  _______ getInWeightlessPhase {
     // ...?
     }

  /** Return the weight of this Treasure.
   * @return the weight of this Treasure.
   */
  double getWeight() {
    // ...?
    }
Brainstorm design issues: How does this interact with grab? Should we fix it? Can we?

Non-constant static fields: idNum

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;

  private double weight;
  private int id;
  // ... other fields omitted

  // constructor
  public Treasure( /* ... */ ) {
    this.id = createdSoFar;
    Treasure.createdSoFar = Treasure.createdSoFar + 1;
    // (Or, if we had declared a (static) getter/setter:
    //    Treasure.setCreatedSoFar( Treasure.getCreatedSoFar()+1 );
    // This is the similar to what we back in PizzaServer's "addToBalance",
    // except that this time it's a static field we're changing, that's all.
    }

  }
Draw a picture of what is happening, when making several Treasures.

Style: People usually don't write getters/setters for static fields. There's no reason you couldn't do that, though. (Should a setter/getter for a static field itself be a static method?                  Does it absolutely have to be?                  What are the drawbacks, if it's not?                 )

Also, note that in the code above, if you leave off the class-name Treasure., java would write it in for you. This only works when referring to a static field/method within the same class you're writing, of course; Player objects would need to refer to Treasure.createdSoFar to refer to that field in the other class. And of course, it would fail since createdSoFar is private, within class Treasure.

If there is left-over time in lecture, we'll talk about test drivers.


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).      

homeinfoexamslectureslabshws
RecipeLawsliessyntaxjava.lang docsjava.util docs


©2007, Ian Barland, Radford University
Last modified 2007.Oct.23 (Tue)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme