Java中构造函数静态代码块代码块的执行顺序

6次阅读

共计 642 个字符,预计需要花费 2 分钟才能阅读完成。

先看一段代码:

package com.wjj.test; 
/**
* @author        作者 : 榨菜哥
* @createTime 创建时间:2018 年 7 月 27 日 下午 3:26:47
* @discription   类说明:* @version       版本:*/
public class ConstructorTest {public static void main(String[] args) {Dog dog = new Dog();
    }

}

class Animal {
    String name;
    int age;
    
    public Animal() {System.out.println("Animal 类");
    }
    
    {System.out.println("Animal 代码块");
    }
    
    static {System.out.println("Animal static 块");
    }
}

class Dog extends Animal {public Dog() {System.out.println("Dog 类");
    }
    
    {System.out.println("Dog 代码块");
    }
    
    static {System.out.println("Dog static 块");
    }
}

执行上面代码输出结果:
Animal static 块
Dog static 块
Animal 代码块
Animal 类
Dog 代码块
Dog 类

总结:

static 代码块、代码块、构造函数的执行顺序为:
父类 static 代码块 > 子类 static 代码块 > 父类代码块 > 父类构造函数 > 子类代码块 > 子类构造函数
(每创建一个对象,就会执行一次非静态代码块)

正文完
 0