加载顺序
简单说:
- 进行静态属性的初始化,若有显性赋值再赋值
- 进行静态代码块的加载(注意是随类的加载而加载的,也就是所只进行一次)
- 再进行非静态的上述步骤,只是转变为非静态,注意(普通代码块是可以多次执行的,它是随着对象被new出来后而执行的)
- 最后在执行构造器
这里有很好的代码说明:
/**
* 代码块 可以对类中的属性进行一些赋值
static:
static
{
}
随着类的加载而执行一次;(所以静态快于非静态执行)
只能操作类中的静态结构;
非static:
{
}
随着对象的创建而执行;
可以操作类中的所有结构;
注意:代码块优先于构造器执行;
* @description
* @author watermelonhit
* @version
* @data 2021年3月13日上午11:50:16
*/
public class BlockTest {
public static void main(String[] args) {
//调用类变量
int num1=Son.id2;
System.out.println("************");
//创建对象
Son son=new Son();//先完成类的加载,再进行对象的创建
System.out.println("***********");
Son son1=new Son();//由于上一次完成的类的加载,故静态代码块不执行了
}
}
class Father{
static int id1=1;
Father(){
System.out.println("this is father constructor");
}
static
{
System.out.println("this is father static block");
}
{
System.out.println("this is father block");
}
}
class Son extends Father{
static int id2=2;
Son()
{
System.out.println("this is son constructor");
}
static
{
System.out.println("this is son static block");
}
{
System.out.println("this is son block");
}
}
输出结果:
this is father static block
this is son static block
************
this is father block
this is father constructor
this is son block
this is son constructor
***********
this is father block
this is father constructor
this is son block
this is son constructor