1. Java对象的初始化顺序如下:
父类 static字段及 static块 -> 子类 static字段及 static块
-> 父类非 static字段及非 static块 -> 父类构造方法
-> 子类非 static字段及非 static块 -> 子类构造方法
2. 示例代码如下:
3. 分析如下:
父类 static字段及 static块 -> 子类 static字段及 static块
-> 父类非 static字段及非 static块 -> 父类构造方法
-> 子类非 static字段及非 static块 -> 子类构造方法
2. 示例代码如下:
package org.demo;
public class InitDemo {
public static void main(String[] args) {
new Child("init");
}
}
class Parent {
private static int total = 1;
private int id = print("id");
private static Parent p1 = new Child("child1");
private static Parent p2 = new Child("child2");
private static int i = print("i");
private static int j = 99;
static {
print("静态块");
}
{
print("构造块");
}
public Parent(String str) {
System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);
++i;
++j;
System.out.println(toString());
}
public static int print(String str) {
System.out.println("parent, " + (total++) + ":" + str + " i=" + i + " j=" + j);
++j;
return ++i;
}
public String toString() {
return "parent, total=" + total + " id=" + id;
}
}
class Child extends Parent {
private static int total = -1;
private int id = -1;
public Child(String name) {
super(name);
if (total < 0) {
total = 1;
} else {
total++;
}
id=total;
System.out.println(toString());
}
public static int print(String str) {
System.out.println(" child, str=" + str);
return 0;
}
public String toString() {
return " child, total=" + total + " id=" + id;
}
}
/*
parent, 1:id i=0 j=0
parent, 2:构造块 i=1 j=1
parent, 3:child1 i=2 j=2
child, total=0 id=0
child, total=1 id=1
parent, 4:id i=3 j=3
parent, 5:构造块 i=4 j=4
parent, 6:child2 i=5 j=5
child, total=1 id=0
child, total=2 id=2
parent, 7:i i=6 j=6
parent, 8:静态块 i=7 j=99
parent, 9:id i=8 j=100
parent, 10:构造块 i=9 j=101
parent, 11:init i=10 j=102
child, total=-1 id=0
child, total=1 id=1
*/