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. 當創建對象的新實例時,除了構造函數中的代碼外,還會運行這些代碼。

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