类中不包含static对象
对象的构造顺序困扰了很久,就在这里做一个整理,如有错误,还希望能够指出。
通常情况下,对于有继承关系的类来说,构造一个子类对象,通常顺序如下:
- 父类静态代码块
- 子类静态代码块
- 父类常量代码块
- 父类构造函数
- 子类常量代码块
- 子类构造函数
测试代码如下:
class Parent{
static{
System.out.println("Parent的静态代码块");
}
{
System.out.println("Parent的常量代码块");
}
public Parent(){
System.out.println("Parent的无参构造函数");
}
}
class Child extends Parent {
static{
System.out.println("Child的静态代码块");
}
{
System.out.println("Child的常量代码块");
}
public Child (){
System.out.println("Child的无参构造函数");
}
}
public class Test{
public static void main(String[] args){
new Child