The Artima Developer Community
Sponsored Link

Yup, can be confusing



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Yup, can be confusing

Posted by Bill Venners on 03 Jun 1998, 1:58 PM

> I am reading your April article in JavaWorld.

> You write that :
> "References to static final variables initialized to a compile-time constant
> are resolved at compile-time to a local copy of the constant value".

> So, apparently, the static initializer is not called when a final
> static member is used. The sample code below illustrates that.
> Don't you think it might be confusing ?

> Sample code :
> public class FinalTest
> {
> public static void main(String argv[]) {
> System.out.println("final = "+Loaded.x);
> // The static initializer of Loaded in the following line :
> System.out.println("non-final = "+Loaded.y);
> }
> }
> class Loaded
> {
> static {
> System.out.println("\tInitialization of Loaded");
> }
> public static final String x = "final";
> public static String y = "non-final";
> }

You're right on both counts. You're right that the use of a
static final field (constant) of a class or interface doesn't
qualify as an active use of that class or interface, which
means it won't trigger the initialization of that class or
interface. And you're right that it can be confusing.

But I think the greatest risk of confusion lies in the fact
that you can change the value of a final static variable in
class Mouse, for example, and if you recompile Mouse, but don't
recompile Cat (which uses the Mouse constant), Cat will still
execute with the old final value. That's going to confuse people
from time to time. Since Cat gets its own local copy of
Mouse's constants, you must recompile Cat if you change the
values of Mouse's constants before Cat will pick up the



Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us