最近在牛客网做面试题,关于类的初始化过程,因为只是测试,所以用了中文命名,不可取。
public class Test_初始化
{
public static int i = 1;
public int j = 2;
public Test_初始化()
{
System.out.println("父类中的构造方法" + i + "---" + j);
}
{
System.out.println("父类中普通的代码块" + i + "---" + j);
}
static
{
System.out.println("父类中的静态代码块" + i);
}
public static void main(String[] args)
{
new test();
}
}
class test extends Test_初始化
{
public static int i = 1;
public int j = 2;
{
System.out.println("子类中普通的代码块" + i + "---" + j);
}
static test1 t = new test1();
public test()
{
System.out.println("子类中的构造方法" + i + "---" + j);
}
static
{
System.out.println("子类中的静态代码块" + i);
}
}
class test1
{
static
{
System.out.println("test1中的静态代码块");
}
{
System.out.println("test1中的非静态代码块");
}
public test1()
{
System.out.println("test1中的构造方法");
}
}
运行结果
总结
类在加载的过程中
1:先初始化父类中的静态成员变量
2: 初始化父类中的静态代码块
3:初始化子类中的静态成员变量
4:初始化子类中的静态代码块
5:初始化父类中的非静态成员变量,代码块
6: 初始化父类的构造函数
7:初始化子类中的非静态成员变量,代码块
8: 初始化子类的构造函数