首先来看看静态构造代码块长啥样子:
static{
...
}
而普通的构造代码块相较之下只是少了一个static关键字
{
...
}
在类的执行过程中,代码块和构造函数、main方法的执行顺序有事什么样的呢?请看如下:
以下示例中包含静态代码块、构造代码块、构造函数。创建了两个对象。
package codeblock;
/**
* 静态方法块只会在最初的时候调用一次
* 但是普通构造方法块在每个对象产生的地方都会调用一次
* 执行顺序:静态代码块 --> main方法 --> 普通构造代码块 --> 构造函数
* @author bamboo
*
*/
public class Block {
private static String name = null;
private static int age = 0;
private static String way = null;
public Block(){
System.out.println("this is father's constructor method");
}
static {
age = 18;
name = "张三";
way = "父亲静态方法块";
System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
}
{
age = 30;
name = "李四";
way = "父亲普通方法块";
System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
}
public static void main(String[] args) {
System.out.println("this is father's main method");
System.out.println();
Block block1 = new Block();
System.out.println();
Block block2 = new Block();
}
}
输出结果如下:
因为接下来这个类会作为父类,所以在输出里面信息说明清楚。
可以看出执行顺序如下:
静态代码块 --> main方法 --> 普通构造代码块 --> 构造函数。
值得注意的是静态代码块只会在最初的时候调用一次,而构造代码块在每次产生对象的时候都会调用。
名字 : 张三 年龄:18 构造: 父亲静态方法块
this is father's main method
名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
子类(SunBlock)继承父类(Block),查看调用顺序。
子类如下:
package codeblock;
public class SunBlock extends Block{
private static String name = null;
private static int age = 0;
private static String way = null;
public SunBlock() {
System.out.println("this is sun's constructor method");
}
static {
age = 1;
name = "小张三";
way = "儿子静态方法块";
System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
}
{
age = 3;
name = "小李四";
way = "儿子普通方法块";
System.out.println("名字 : " + name + " 年龄:" + age + " 构造: " + way);
}
public static void main(String[] args) {
System.out.println("this is sun's main method");
System.out.println();
SunBlock sun1 = new SunBlock();
System.out.println();
SunBlock sun2 = new SunBlock();
}
}
执行结果:
名字 : 张三 年龄:18 构造: 父亲静态方法块
名字 : 小张三 年龄:1 构造: 儿子静态方法块
this is sun's main method
名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
名字 : 小李四 年龄:3 构造: 儿子普通方法块
this is sun's constructor method
名字 : 李四 年龄:30 构造: 父亲普通方法块
this is father's constructor method
名字 : 小李四 年龄:3 构造: 儿子普通方法块
this is sun's constructor method
可以看出执行顺序如下:
父类的静态代码块 --> 子类的静态代码块 -->main函数 --> 父类构造代码块 --> 父类构造函数 --> 子类构造代码块 --> 子类构造函数。