静态初始化块与构造函数java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18605974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:26:48  来源:igfitidea点击:

static initialization block vs constructor java

java

提问by UnderDog

class prog
{
    static
    {
        System.out.println("s1");
    }
    prog()
    {
        System.out.println("s2");
    }

    public static void main(String...args)
    {
        prog p = new prog();
    }
}

Output is

输出是

s1
s2

As per the output, it seems that static initialization block gets executed before the default constructor itself is executed.

根据输出,似乎在执行默认构造函数本身之前执行了静态初始化块。

What is the rationale behind this?

这背后的原理是什么?

采纳答案by Joachim Sauer

Strictly speaking, static initializersare executed, when the class is initialized.

严格来说,静态初始化在类初始化时执行。

Class loadingis a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it ispossible to load a class without initializing it (for example by using the three-argument Class.forName()variant).

类加载是一个单独的步骤,它发生得稍早一些。通常一个类被加载然后立即初始化,所以大多数时候时间并不重要。但它可以装载一个类不具有(通过使用例如初始化它的三个参数的Class.forName()变体)。

No matter which way you approach it: a class will alwaysbe fully initialized at the time you create an instance of it, so the staticblock will already have been run at that time.

无论您采用哪种方式处理它:在您创建一个类的实例时,它总是会被完全初始化,因此该static块在那个时候已经运行了。

回答by Jigar Joshi

That is right static initialization is being done when class is loaded by class loader and constructor when new instance is created

这是正确的静态初始化是在创建新实例时由类加载器和构造函数加载类时进行的

回答by Subhrajyoti Majumder

Static blockexecuted once at the time of class-loading & initialisation by JVM and constructor is called at the every time of creating instance of that class.

Static block在类加载和 JVM 初始化时执行一次,并且在每次创建该类的实例时调用构造函数。

If you change your code -

如果您更改代码 -

public static void main(String...args){
    prog p = new prog();
    prog p = new prog();
}

you'll get output -

你会得到输出 -

s1 // static block execution on class loading time
s2 // 1st Object constructor
s2 // 2nd object constructor

Which clarifies more.

这说明了更多。

回答by sasi

Static block one time execution block.. it executes while class loading..

静态块一次执行块..它在类加载时执行..

when object is created for a class constructor executes..

当为类构造函数创建对象时执行..