Java中的静态块[重复]

本文翻译自:Static Block in Java [duplicate]

This question already has answers here : 这个问题已经在这里有了答案
Closed 4 years ago . 4年前关闭。

I was looking over some code the other day and I came across: 前几天,我在查看一些代码,然后发现:

static {
    ...
}

Coming from C++, I had no idea why that was there. 来自C ++,我不知道为什么会这样。 Its not an error because the code compiled fine. 它不是错误,因为代码编译良好。 What is this "static" block of code? 这个“静态”代码块是什么?


#1楼

参考:https://stackoom.com/question/CLki/Java中的静态块-重复


#2楼

Static blocks are used for initializaing the code and will be executed when JVM loads the class.Refer to the below link which gives the detailed explanation. 静态块用于初始化代码,并将在JVM加载类时执行。请参考以下链接,其中提供了详细说明。 http://www.jusfortechies.com/java/core-java/static-blocks.php http://www.jusfortechies.com/java/core-java/static-blocks.php


#3楼

静态块在任何程序的生命周期中执行一次,静态块的另一个属性是它在main方法之前执行。


#4楼

Static block can be used to show that a program can run without main function also. 静态块可以用来表明程序也可以在没有主要功能的情况下运行。

//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
    static
    {
        System.out.println("Welcome to Java"); 
        System.exit(0); 
    }
}

#5楼

yes, static block is used for initialize the code and it will load at the time JVM start for execution. 是的,静态块用于初始化代码,它将在JVM启动执行时加载。

static block is used in previous versions of java but in latest version it doesn't work. 静态块在Java的早期版本中使用,但在最新版本中不起作用。


#6楼

It's a static initializer . 这是一个静态初始化器 It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference). 它是在加载类时执行的(确切地说是初始化,但通常不会注意到它们之间的区别)。

It can be thought of as a "class constructor" . 可以将其视为“类构造函数”

Note that there are also instance initializers , which look the same, except that they don't have the static keyword. 请注意,还有一些实例初始化器 ,它们看起来一样,只是它们没有static关键字。 Those are run in addition to the code in the constructor when a new instance of the object is created. 当创建对象的新实例时,除了构造函数中的代码外,还会运行这些代码。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章