笔试题总结——代码块的执行顺序
看代码块的执行顺序之前,首先来看一下代码块的一下相关概念,代码块分为四种,普通代码块,构造代码块,静态代码块,同步代码块(暂且不谈)。
1、普通代码块(了解即可):定义在
方法
中的代码块(没有任何修饰符)
2、构造代码块:定义在类中
的代码块(没有任何修饰符),在对象产生时优先于构造方法执行
,有几个对象产生,就调用几次构造代码块,用于在构造方法前完成一些初始化工作。
3、静态代码块:在类加载时执行
,优先于构造代码块,无论有多少对象产生,只会调用一次。若是主类(public class)中的静态代码块,还会优先于主方法(main方法),只会执行一次
。
看完了代码块的定义后,主要说一下构造方法,构造代码块与静态代码块之间的执行优先级。
静态代码块 > 构造代码块 > 构造方法
举个栗子验证一下(故意调整一下顺序):
public class CodeBlock {
public CodeBlock(){
System.out.println("this is constructor");
}
{
System.out.println("This is construct block");
}
static {
System.out.println("This is static block");
}
public static void main(String[] args) {
System.out.println("This is main");
CodeBlock codeBlock1 = new CodeBlock();
CodeBlock codeBlock2 = new CodeBlock();
}
}
打印结果如下:
This is static block
This is main
This is construct block
this is constructor
This is construct block
this is constructor
分析一下这个打印结果,可以看出,静态代码块在类加载时被调用,优先级高于main()方法,且只会被调用一次(与类对象的个数无关),构造代码块的优先级是高于构造方法的,且每创建一个类对象,就会调用一次构造代码块。
然而,这并不是代码块执行顺序的结束,而只是开始,代码块执行顺序
一般是结合继承
作为一道题考察。接下来,就看真正的重头戏。
class Animal{
public Animal(){
System.out.println("this is Animal constructor");
}
{
System.out.println("This is Animal construct block");
}
static {
System.out.println("This is Animal static block");
}
}
class Dog extends Animal{
public Dog(){
System.out.println("this is Dog constructor");
}
{
System.out.println("This is Dog construct block");
}
static {
System.out.println("This is Dog static block");
}
}
public class CodeBlock {
public static void main(String[] args) {
Dog dog = new Dog();
}
}
打印结果如下:
This is Animal static block
This is Dog static block
This is Animal construct block
this is Animal constructor
This is Dog construct block
this is Dog constructor