next up previous contents
Next: Constructors Up: Data encapsulation with classes Previous: Static components   Contents

Constants (the attribute final)

Consider our earlier definition

  class Math {
    public static double PI = 3.1415927;
    ...
  }

The intention was to make the value Math.PI available everywhere to use in expressions: e.g.,

  area = Math.PI * radius * radius;

However, there is nothing to prevent the following improper update of the public static field PI:

  Math.PI = 3.25;

To forbid this, we attach another attribute, indicating that a value but may not be altered. Following Java terminology, we use the notation final, so we would modify the definition above to say:

  class Math {
    public static final double PI = 3.1415927;
    ...
  }

and achieve what we set out to have--a publicly available constant that exists without instantiating any objects.

Actually, the modifier final has other ramifications. We will see these later, when we talk about inheritance.



Madhavan Mukund 2004-04-29