java中类的方法初始化顺序

类初始化时构造函数调用顺序:

(1)初始化对象的存储空间为零或null值;

(2)调用父类构造函数;

(3)按顺序分别调用类成员变量和实例成员变量的初始化表达式;

(4)调用本身构造函数。

例子:

public class Dog extends Animal{
 Cat c=new Cat();

 public Dog(){

  System.out.println("Dog 构造方法!");

 }
 public static void main(String[] args){

  new Dog();

 }
}
class Animal{
 public Animal(){
  System.out.println("Animal构造方法");
 }
}
class Cat{
 public Cat(){
  System.out.println("Cat 构造方法");
 }
}

输出结果:

Animal构造方法

Cat 构造方法

Dog 构造方法

在我们的程序中,实例化一个类对象的时候,运行顺序为:

静态块

父类构造器

本类中的块

本类的构造器

public class Dog {   
   public Dog() {   
 System.out.println("Dog");   
}   
static{   //静态块
    System.out.println("super static block");   
}       
{   
    System.out.println("super block");   
}   
}  
public class Mastiff extends Dog {   
public Mastiff() {   
    System.out.println("Mastiff");   
}   
 {   
    System.out.println("block");   
   }   
static {   
  System.out.println("static block");   
}   
public static void  main(String[] args){   
  Mastiff mastiff=new Mastiff();         //实例化一个对象
}   
}   

输出结果:

super static block

static block

super block

Dog

block

Mastiff

也就是说此时的运行顺序为:

  1. 父类静态块
  2. 自身静态块
  3. 父类块
  4. 父类构造器
  5. 自身块
  6. 自身构造器
文章目录
|