javastatic-membersobjectinstantiation

Will static variable in non-instantiated class be initialized via call to Toolkit?


I want to be able to adjust click interval in a program IF the user wishes to do so, at which point class ClickAdjustmentFrame would be instantiated.

It had seemed sensible to have CLICK_FREQUENCY initialized in the only class where its value could be changed. So that class began like this :

public class ClickAdjustmentFrame {

    static int CLICK_FREQUENCY = ((Integer)Toolkit.getDefaultToolkit()
      .getDesktopProperty("awt.multiClickInterval"));

Because that class isn't always instantiated, that class now imports the value of CLICK_FREQUENCY from the GUI class, where I moved the statement in question. (I.e., GUI now begins like this:)

public class GUI {

   static int CLICK_FREQUENCY = ((Integer)Toolkit.getDefaultToolkit()
          .getDesktopProperty("awt.multiClickInterval"));

But before making the change, during debugging, it seemed that the call to Toolkit was being made even if ClickAdjustmentFrame had NOT been instantiated. At first that wasn't surprising. Then I began questioning the design and so moved the call to Toolkit to GUI.

It doesn't matter anymore in terms of my app, but for the record and for educational purposes, if the call to Toolkit were made nowhere else, WOULD THE VALUE OF CLICK_FREQUENCY BE COMPUTED and available to the rest of the package even if class ClickAdjustmentFrame (as shown below) were NOT instantiated?

public class ClickAdjustmentFrame {

    static int CLICK_FREQUENCY = ((Integer)Toolkit.getDefaultToolkit()
      .getDesktopProperty("awt.multiClickInterval"));
...

I know that I could call a static method in a non-instantiated class (and do so quite often), but this is about static variables being initialized via a call to a static method somewhere else.

Exactly what very basic principle applies here? Is it that all static members of any class are available to other classes in the package?

Maybe a better question is this: Is it more sensible (better design) to move the call to Toolkit back to ClickAdjustmentFrame, the only class where the value of CLICK_FREQUENCY can be changed?


Solution

  • Static fields are initialised the first time the class is loaded by the classloader. See this SO.

    For instance, if a static field of the class ClickAdjustmentFrame is accessed, there is no instance, but all static initialisations of the class will occur.