After the necessary classes have all been loaded, so the object can be created. First, all the primitives in this object are set to their default values and the object references are set to null —this happens in one fell swoop by setting the memory in the object to binary zero. Then the base-class constructor is called.
All static objects and static code blocks are initialized in textual order (the order you write them in the class definition), at load time. The statics are initialized only once.
After the base-class constructor completes, the instance variables are initialized in textual order. Finally, the rest of the body of the constructor is executed.
// reuse/Beetle.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// The full process of initialization
class Insect {
private int i = 9;
protected int j;
static {
System.out.println("static code block.");
}
{
System.out.println("normal code block.");
}
Insect() {
System.out.println("i = " + i + ", j = " + j);
j = 39;
}
private static int x1 = printInit("static Insect.x1 initialized");
static int printInit(String s) {
System.out.println(s);
return 47;
}
}
public class Beetle extends Insect {
private int k = printInit("Beetle.k initialized");
public Beetle() {
System.out.println("k = " + k);
System.out.println("j = " + j);
}
private static int x2 = printInit("static Beetle.x2 initialized");
public static void main(String[] args) {
System.out.println("Beetle constructor");
// new Insect(); // [1]
Beetle b = new Beetle(); // [2]
}
}
/* My Output:
static code block.
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
normal code block.
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
*/
// when commented [2], uncommented [1], Output:
/*
static code block.
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
normal code block.
i = 9, j = 0
*/
for better understand, please read below content.
see static explicit data initialization.
references:
1. On Java 8 - Bruce Eckel
2. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/reuse/Beetle.java
本文详细解析了Java中对象初始化的过程,包括静态成员和实例成员的初始化顺序,以及构造函数的执行流程。通过具体代码示例,展示了初始化过程中各部分的执行顺序,帮助读者深入理解Java对象创建的机制。
1338

被折叠的 条评论
为什么被折叠?



