当前位置: 动力学知识库 > 问答 > 编程问答 >

Java constructor vs inline field initialisation

问题描述:

This question already has an answer here:

  • Are fields initialized before constructor code is run in Java?

    4 answers

网友答案:

I'm wondering in both cases will it actually initially assign 5, and then update this with 10

Yes. The constructor will:

  1. Call super().
  2. Execute any inline initializations and anonymous initialization blocks.
  3. Execute the remaining body of the constructor.

This is specified in more detail in the JLS #12.5-6.

网友答案:

The compiler will not do such kinds of optimization - there is actually no point in doing such a micro-optimization (you can make sure using javap).

Furthermore the language specification dictates that such values be assigned in some order. And these steps should logically be different steps that are not combined.

网友答案:

Simple flow is:
1. Parent class initialization
2. Static fields and static sections initialization in the order they occur in the source file
3. Fields initialization and instance sections initialization in the order they occur in the source file
4. Constructor execution

Example:

public class TestClass {
    private int a = 5;
    {
        a = 10; 
    }

    private static int b = 10;

    static {
        b = 15;
    }

    public TestClass() {
        System.out.println(a + ", " + b);
        a = 20;
        b = 30;
        System.out.println(a + ", " + b);
    }

    public static void main(String args[]) {
        TestClass t = new TestClass();
    }
}

Output:

10, 15
20, 30
网友答案:

When JVM loads the class, it actually loads Test.class and allocates memory for static variables such as y. Any member variables such as x will only be initialized upon construction of object like new Test();

网友答案:

When you declare a variable using an assignment statement like that, the value becomes the default value for the variable. If you don't change it, it will always return that value. If you do overwrite the default value, it will return the new one instead

分享给朋友:
您可能感兴趣的文章:
随机阅读: