سؤال

Consider this:

Class A
{
   private static B b = new B();
   private static C c;

   static
   {
     c= new C();
   }
}
  1. Is the initialization of b occur on class load?
  2. Same question for initialization of c
  3. What happends first initalization of b or c?
    Please give me a reference for java docs regarding this issues if exists.

Thanks

هل كانت مفيدة؟

المحلول

Class variables are initialized at class load time, in textual order, as though they were a single block, so b is initialized first then c, as noted in step 9 of the Detailed Initialization Procedure defined in the Java Language Specification.

نصائح أخرى

The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

Static initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

static block

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top