2

Consider a Java class with static fields only and no constructor:

public class OnlyStatic {
   static O1 o1 = new o1();
   static O2 o2 = new o2();

   public static int compute(int whatever) {
       return o1.foo+o2.bar+whatever;
   }
}

In a different class, the method compute is used, either by static import:

static import OnlyStatic.compute
int a = OnlyStatic.compute(3);

Or directly, assuming the caller is in the same package:

int a = OnlyStatic.compute(3);

When are o1 and o2 initialized? At the import, or when compute() is called for the first time?

Community
  • 1
  • 1
Adam Matan
  • 128,757
  • 147
  • 397
  • 562

1 Answers1

5

The objects o1 and o2 are not available to your static context without making them static also.

JVMS states that

Any static initializers declared in a class are executed when the class is initialized

Further

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested within T is executed.

So in your case, when the static method compute() is first executed.

Johan Sjöberg
  • 47,929
  • 21
  • 130
  • 148
  • Fixed the static declaration. What do you mean by directly? At the import, or at the first call? – Adam Matan Feb 20 '12 at 13:08
  • "...not lazy-loaded". Strictly speaking this is not true. The class `OnlyStatic` is lazy loaded by the JVM. But the static fields are initialized immediately during the loading of the class. – A.H. Feb 20 '12 at 13:08
  • @A.H. - is the class first loaded upon import or upon method call? – Adam Matan Feb 20 '12 at 13:11
  • 1
    @AdamMatan: `import` is only known to the compiler, at runtime there is no `import`. Besides of this you might read this question: http://stackoverflow.com/q/8550567/947357 – A.H. Feb 20 '12 at 13:14