继承中的静态块vs初始化器块vs构造函数 [英] static block vs initializer block vs constructor in inheritance

查看:95
本文介绍了继承中的静态块vs初始化器块vs构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了这个例子,我想了解它背后的逻辑吗?构造函数,静态块和初始化程序块如何在继承中工作?在每个阶段都被称为?

i find this example and i want to understand the logic behind it ? how constructors and static blocks and initializer blocks works in inheritance ? in which stage each one is called ?

public class Parent {

    static {
        System.out.println("i am Parent 3");
    }

    {
        System.out.println("i am parent 2");
    }

    public Parent() {
        System.out.println("i am parent 1");
    }

}

public class Son extends Parent {

    static {System.out.println("i am son 3");}
    {System.out.println("i am son 2");}

    public Son() {
        System.out.println("i am son 1");
    }

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

输出为:

i am Parent 3
i am son 3
i am parent 2
i am parent 1
i am son 2
i am son 1

推荐答案

当该类由JVM加载并初始化时,将调用一次静态块.实例构造器是在构造类的实例时执行的,就像构造函数一样.

A static block is called once, when the class is loaded and initialized by the JVM. An instance initializer is executed when an instance of the class is constructed, just like a constructor.

静态和实例初始化程序

Static and Instance initializers are described in the Java Language Specification

这篇关于继承中的静态块vs初始化器块vs构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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