简体   繁体   English

Java实例初始化块和实例变量

[英]Java Instance Initialization Block and instance variables

In context to my previous question Java classes and static blocks what if I changed my code from static block and variables to normal Instance Initialization Block and instance variables. 在上一个问题的上下文中,如果我将代码从静态块和变量更改为普通的实例初始化块和实例变量,那么Java类和静态块会怎样。 Now how would the code be executed? 现在如何执行代码?

class extra3 {
    public static void main(String string[]) {
        Hello123 h = new Hello123();
        System.out.println(h.a);
    }
}
class Hello123 {
    {
        a=20;
    }
    int a=158;
}

Here I am getting output as 158. I am not able to understand the reason here.And the other code being this: 在这里,我输出为158.我无法理解这里的原因。其他代码是这样的:

class extra3 {
    public static void main(String string[]) {
        Hello123 h = new Hello123();
        System.out.println(h.a);
    }
}
class Hello123 {
    int a=158;
    {
        a=20;
    }
}

Here the output is 20 which is acceptable because when object is created Instance block is executed first. 这里的输出是20,这是可以接受的,因为创建对象时首先执行实例块。 But why is the output in first code coming as 158? 但为什么第一个代码的输出为158?

This is the order of initialization 这是初始化的顺序

  1. Set fields to default initial values (0, false, null) 将字段设置为默认初始值(0,false,null)
  2. Call the constructor for the object (but don't execute the body of the constructor yet) 调用对象的构造函数(但是不要执行构造函数的主体)
  3. Invoke the constructor of the superclass 调用超类的构造函数
  4. Initialize fields using initializers and initialization blocks 使用初始化程序和初始化块初始化字段
  5. Execute the body of the constructor 执行构造函数的主体

So, when you are initializing fields, both inline initializer ( a = 158 ) and initialization blocks ( a = 20 ) are executed in the order as they have defined. 因此,在初始化字段时,内联初始值设定项( a = 158 )和初始化块( a = 20 )将按其定义的顺序执行。

So in the first case, inline initializer executed after the initialization block, you get 158 as result. 所以在第一种情况下,在初始化块之后执行内联初始化程序,结果得到158。

In the second case, initialization block got executed after inline initializer. 在第二种情况下,初始化块在内联初始化器之后执行。

Order matters. 订单很重要。

Initialization's and static blocks executes based on the order they placed in source code. 初始化和静态块基于它们放置在源代码中的顺序执行。 That's the reason. 这就是原因。

Static blocks are executed in the order they are declared in code. 静态块按照它们在代码中声明的顺序执行。 This article will help you understand the order of execution of static and non static initlaization blocks 文章将帮助您了解静态和非静态initlaization块的执行顺序

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

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