Java 中靜態塊和建構函式的區別是什麼?
靜態塊
- 靜態塊在類載入時執行。
- 靜態塊在執行main() 方法之前執行。
- 靜態塊在其原型中沒有名稱。
- 如果我們希望在類載入時執行任何邏輯,則需要將該邏輯放在靜態塊中,以便在類載入時執行。
語法
static { //some statements }
示例
public class StaticBlockTest { static { System.out.println("Static Block!"); } public static void main(String args[]) { System.out.println("Welcome to Tutorials Point!"); } }
輸出
Static Block! Welcome to Tutorials Point!
建構函式
- 在Java 中,建構函式在建立物件時執行。
- 在建立類物件時呼叫建構函式。
- 建構函式的名稱必須始終與類名相同。
- 建構函式每個物件只調用一次,並且可以根據建立物件的次數呼叫多次。即在建立物件時自動執行建構函式。
語法
public class MyClass { //This is the constructor MyClass() { // some statements } }
示例
public class ConstructorTest { static { //static block System.out.println("In Static Block!"); } public ConstructorTest() { System.out.println("In a first constructor!"); } public ConstructorTest(int c) { System.out.println("In a second constructor!"); } public static void main(String args[]) { ConstructorTest ct1 = new ConstructorTest(); ConstructorTest ct2 = new ConstructorTest(10); } }
輸出
In Static Block! In a first constructor! In a second constructor!
廣告