class Mid extends Root{
static {
System.out.println("Mid的静态初始化块");
}
{
System.out.println("Mid的普通初始化块");
}
public Mid() {
super();
System.out.println("Mid的无参构造器");
}
public Mid(String info) {
this();
System.out.println("Mid的带参构造器,其参数为:" + info);
}
}
class Root{
static {
System.out.println("Root的静态初始化块");
}
{
System.out.println("Root的普通初始化块");
}
public Root() {
System.out.println("Root的无参构造器");
}
}
class Leaf extends Mid{
static {
System.out.println("Leaf的静态初始化块");
}
{
System.out.println("Leaf的普通初始化块");
}
public Leaf() {
super("非常6+1");
System.out.println("Leaf的无参构造器");
}
}
public class LeafTest {
public static void main(String[] args) {
new Leaf();
}
}
运行结果为:
总结:代码块的编译优先于构造器
并且同为静态初始化块时,从根类向下进行。
在代码块中对属性赋值: