根據代碼塊定義的位置以及關鍵字,可以分爲以下四種:
- 普通代碼塊
- 構造代碼塊
- 靜態塊
- 同步代碼塊
一、普通代碼塊
定義在方法中的代碼塊,如:
//直接使用{}定義
public class Main {
public static void main(String[] args) {
{
int x = 1;
System.out.println("x = " + x);
}
{
int y = 2;
System.out.println("y = " + y);
}
}
}
二、構造代碼塊
定義在類中的代碼塊(不加修飾符),也稱實例代碼塊,一般用於初始化實例成員變量。如:
class Student{
private String name;
private int age;
//構造函數
public Student(){
System.out.println("we are winner");
}
//構造代碼塊
{
this.age = 20;
this.name = "jack";
System.out.println("I am the best");
}
public void show(){
System.out.println("name:" + name + " age:" + age);
}
}
public class Main {
public static void main(String[] args) {
Student student = new Student();
student.show();
}
}
輸出:
I am the best
we are winner
name:jack age:20
注意:實例代碼塊優先於構造函數執行。
三、靜態代碼塊
使用static定義的代碼塊,一般用於初始化靜態成員屬性。如:
class Student{
private String name;
private int age;
private static int count = 0;//靜態成員變量,存於共享區
//構造函數
public Student(){
System.out.println("we are winner");
}
//構造代碼塊(實例代碼塊)
{
this.age = 20;
this.name = "Run";
System.out.println("I am the best");
}
//靜態代碼塊
static {
count = 10;
System.out.println("I am static and count = " + count);
}
public void show(){
System.out.println("name:" + name + " age:" + age);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
Student student2 = new Student();
student1.show();
student2.show();
}
}
輸出:
I am static and count = 10
I am the best
we are winner
I am the best
we are winner
name:Run age:20
name:Run age:20
注意事項:
- 不管生成多少個對象,靜態代碼塊只會執行一次,且是最先執行。
- 靜態代碼塊執行完畢後,實例代碼塊(構造塊)執行,再構造函數執行。