문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top