简体   繁体   English

Java中的静态初始化

[英]static initialization in java

I know there are a lot of questions similar to this one , but i would like to get some detailed explanation about this issue. 我知道有很多与此问题类似的问题,但是我想对此问题进行一些详细的解释。

Let say that i have this code - 假设我有此代码-

 public class Finalexamples {

        public int num = 3;
        public static int num2;
        public static Finalexamples a;

        public Finalexamples(){
            Finalexamples.num2 = 4;
        }

        static{
            a = new Finalexamples();
             System.out.println(num2);
             Finalexamples.num2 = 5;
            }

    public static void main(String[] args) {
        System.out.println("Starting...");
    }

}
  1. When the JVM loads a .class file, does it first initialize the static variables with a default value, and afterward when the program running with the literal value? 当JVM加载.class文件时,它是否首先使用默认值初始化静态变量,然后在程序使用文字值运行时是否初始化它?
  2. In my example, the static block outputs "4" (fixed), if one can explain why isn't it 0? 在我的示例中,静态块输出“ 4”(固定),如果可以解释为什么它不是0?

Why 0 ? 为什么是0 It should output 4 rather. 它应该输出4而不是。

When the class is loaded, the static fields and statements are read and executed in the order of apparition. 加载类时,将按固定顺序读取并执行静态字段和语句。

So these are executed first : 所以这些首先执行:

public static int num2;
public static Finalexamples a;

Then this is invoked : 然后调用:

 static{
          a = new Finalexamples();
          System.out.println(num2);
          Finalexamples.num2 = 5;
      }

This : a = new Finalexamples(); 这是: a = new Finalexamples(); executes : Finalexamples.num2 = 4; 执行: Finalexamples.num2 = 4;

So System.out.println(num2); 所以System.out.println(num2); displays 4 显示4

Ok, so first Java goes to your topmost static declaration in the class (defining num2 As an int) then it defines a as a Finalexamples object. 好的,因此,首先Java转到类中最顶层的静态声明(将num2定义为int),然后将a定义为Finalexamples对象。 It then goes to your static block. 然后转到您的静态块。 In the static block, it sees a = new Finalexamples(); 在静态块中,它看到a = new Finalexamples(); so it then goes to create a via the constructor. 因此,它将通过构造函数创建a (If it didn't do this step until the end of static initialization, a would be inaccessible until the end, since it wasn't constructed, which is not good!) So in our constructor for the variable a we set Finalexamples.num2 equal to 4. The constructor is done and Java returns to executing the static block, and prints out Finalexamples.num2 , which is now 4. (如果直到静态初始化结束才执行此步骤,则a直到结束都将无法访问,因为它没有被构造,这是不好的!)因此,在变量a构造函数中,我们设置了Finalexamples.num2等于4。构造函数完成,Java返回执行静态块,并打印出Finalexamples.num2 ,现在为4。

Know this flow first(this is for your program only), 首先了解此流程(仅适用于您的程序),

  1. Initialization of static variable. 静态变量的初始化。

     public static int num2; public static Finalexamples a; 

  2. Execution of static block: 静态块的执行:

     static{ a = new Finalexamples(); System.out.println(num2); Finalexamples.num2 = 5; } 
  3. As you are initializing the object reference 'a' of Finalexamples in static block, the constructor of Finalexamples class will be called. 在静态块中初始化Finalexamples的对象引用“ a”时,将调用Finalexamples类的构造函数。

     public Finalexamples(){ Finalexamples.num2 = 4; } 

  4. The Finalexamples.main() method. Finalexamples.main()方法。 Which has nothing. 哪个都没有。

     public static void main(String[] args) { System.out.println("Starting..."); } 

Answering your questions. 回答您的问题。

A. Static variables are initialized only once , at the start of the execution .These variables will be initialized first, before the initialization of any instance variables. A.静态变量在执行开始时仅初始化一次。这些变量将在任何实例变量初始化之前首先进行初始化。 It is a variable which belongs to the class and not to object(instance). 它是属于该类而不属于object(instance)的变量。 A single copy to be shared by all instances of the class 该类的所有实例共享一个副本

B. It's not '0' becuase you are initializing the object reference in static block with new object of Finalexamples. B.不是'0'因为您正在使用Finalexamples的新对象在静态块中初始化对象引用。 At this time the constructor will be called and it will set the vaule of num2 to 4 . 这时将调用构造函数,并将num2的值设置为4

I hope this help! 希望对您有所帮助!

hi your final output is 5 in java you two section first is Class Area and second is Heap area class area block contains three block method area,static area,constant pool.static block is run when class loading so your static variable is created in static block it is initialize at the run time of static block and for static variable multiple copy will not created in java so you can test your code like this 您在Java中的最终输出是5,您的两个部分首先是类区域,其次是堆区域类区域块包含三个块方法区域,静态区域,常量池。在类加载时运行static块,因此您的静态变量是在static中创建的块它在静态块的运行时初始化,并且对于静态变量,不会在Java中创建多个副本,因此您可以像这样测试代码

public class HelloWorld{

    public int num = 3;
    public static int num2;
    public static HelloWorld a;

    public HelloWorld(){
         System.out.println("Constructor Creation value of num2 "+num2);
         HelloWorld.num2 = 4;
         System.out.println("Variable Initialization in Constructor value of num2 "+num2);
    }

    static{

         System.out.println("Static bloack execution  value of num2 "+num2);
          a = new HelloWorld();
         HelloWorld.num2 = 5;
         System.out.println("Variable Initialization in Static bloack value of num2 "+num2);
        }

public static void main(String[] args) {
    System.out.println("Starting...");
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM