当使用继承时,静态块和初始化块执行什么顺序? [英] In what order do static blocks and initialization blocks execute when using inheritance?

查看:141
本文介绍了当使用继承时,静态块和初始化块执行什么顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个类Parent和Child

I have two classes Parent and Child

public class Parent {    
    public Parent() {
        System.out.println("Parent Constructor");
    }    
    static {
        System.out.println("Parent static block");    
    }    
    {
        System.out.println("Parent initialisation  block");
    }
}

public class Child extends Parent {    
    {
        System.out.println("Child initialisation block");
    }
    static {
        System.out.println("Child static block");
    }

    public Child() {
        System.out.println("Child Constructor");
    }    
    public static void main(String[] args) {
        new Child();    
    }
}

上述代码的输出将是

Parent static block
Child static block
Parent initialization  block
Parent Constructor
Child initialization block
Child Constructor

为什么Java以该顺序执行代码?

Why does Java execute the code in that order? What are the rules that determine the execution order?

推荐答案

有几个规则正在执行


  • 静态块始终在创建对象之前运行,这就是为什么您会看到来自父项和子项静态块的打印消息

  • ,当你调用子类(child)的构造函数时,这个构造函数会在执行它自己的构造函数之前隐式调用 super(); 。初始化块甚至在构造函数调用之前就会起作用,所以这就是为什么它被首先调用。所以现在你的父被创建,程序可以继续创建子类,将经历相同的过程。

  • static blocks are always run before the object is created, so that's why you see print messages from both parents and child static blocks
  • now, when you are calling constructor of the subclass (child), then this constructor implicitly calls super(); before executing it's own constructor. Initialization block comes into play even before the constructor call, so that's why it is called first. So now your parent is created and the program can continue creating child class which will undergo the same process.

说明


  1. 首先执行父块的静态块,因为它首先加载 ,并且在加载类时调用静态块。

  1. Static block of parent is executed first because it is loaded first and static blocks are called when the class is loaded.


这篇关于当使用继承时,静态块和初始化块执行什么顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆