静态代码块,构造代码块,main()
静态代码块
- 随Class 加载而加载,为Class 作初始化;
- 在main() 之前加载;
- 只执行一次;
构造代码块
- 随对象的创建而加载,为对象作初始化
public class day04 {
public static day04 d1 = new day04();
//public static day04 d2 = new day04();
public day04(){
System.out.println("构造方法");
}
{
System.out.println("构造代码块");
}
static {
System.out.println("静态代码块");
}
public static void main(String[] args) {
System.out.println("main()");
//day04 d = new day04();
}
}
输出顺序:
1.构造代码块
2.构造方法
3.静态代码块
4.main()
public class day04 {
public static day04 d1 = new day04();
//public static day04 d2 = new day04();
public day04(){
System.out.println("构造方法");
}
{
System.out.println("构造代码块");
}
static {
System.out.println("静态代码块");
}
public static void main(String[] args) {
System.out.println("main()");
day04 d = new day04();
}
}
输出顺序:
1.构造代码块
2.构造方法
3.静态代码块
4.main()
5.构造代码块
6.构造方法
main()
- 静态代码块在main() 方法之前加载:
public class day04 {
//public static day04 d1 = new day04();
//public static day04 d2 = new day04();
public day04(){
System.out.println("构造方法");
}
{
System.out.println("构造代码块");
}
static {
System.out.println("静态代码块");
}
public static void main(String[] args) {
System.out.println("main()");
//day04 d = new day04();
}
}
输入结果:
1. 静态代码块
2. main()