構造程式碼塊與靜態構造程式碼塊
阿新 • • 發佈:2021-01-02
構造程式碼塊與靜態構造程式碼塊
Syntax
[修飾符] ... class [類名] { [修飾符] [static] ... [型別][靜態屬性] ... [修飾符] ... [型別][普通屬性] ... static { //靜態構造程式碼塊 ... } { //構造程式碼塊 ... } [修飾符] ... [構造方法](){ ... } [修飾符] ... [返回值] [普通方法]() { ... } }
構造程式碼塊與靜態構造程式碼塊是一種特殊的應用,會在類的誕生和物件的誕生進行呼叫
靜態構造程式碼塊被用作對靜態變數進行初始化
構造程式碼塊在實際運用中較少
用一段程式碼來解釋
public class Student { static String name; int age; String id; static { System.out.println(name); System.out.println("我是靜態構造程式碼塊"); System.out.println("static{...}"); name = "static{...}"; //這裡不能用this.name ,因為this表示物件自己,但這個時候不可能有物件 } { System.out.println("this.name="+this.name); System.out.println("我是構造程式碼塊"); System.out.println("{...}"); this.name = "{...}"; } public Student() { System.out.println("this.name="+this.name); System.out.println("我是構造方法"); this.name = "hello world..."; this.age = -1 ; this.id = "null" ; } public static void main(String[] args) { Student student = new Student(); System.out.println("name="+student.name); System.out.println("age="+student.age); System.out.println("id="+student.id); System.out.println("========================"); Student student1 = new Student(); // 再new一個看看結果 } }
輸出結果
null
我是靜態構造程式碼塊
static{...}
this.name=static{...}
我是構造程式碼塊
{...}
this.name={...}
我是構造方法
name=hello world...
age=-1id=null
========================
this.name=hello world...
我是構造程式碼塊
{...}
this.name={...}
我是構造方法
結論
一類的誕生到一個物件誕生的細節
- 類誕生了
- 建立靜態變數
- 呼叫靜態構造程式碼塊
- 物件誕生了
- 建立普通變數
- 呼叫構造程式碼塊
- 呼叫構造方法
- ......
注意:靜態構造程式碼塊只執行一次,也就是類誕生的那一次,因為類的誕生在程式運行當中只進行一次。
在實際實驗當中,main方法再次new了一個物件,但是沒有執行靜態構造程式碼塊的語句