java中的代碼塊
簡述
1.局部代碼塊:
在方法中出現;限定變量生命週期,及早釋放,提高內存利用率
2.構造代碼塊:
構造代碼塊分爲有參構造代碼塊和無參構造代碼塊,會在創建對象時被調用,優先於類構造函數執行
3.靜態代碼塊
用static{}包裹起來的代碼塊,只執行一次,優先於構造代碼塊執行
4.同步塊
後面多線程會學到,到時候再來填坑
靜態代碼塊和構造代碼塊的特點
靜態代碼塊:
1.定義在類中方法外,用static修飾
2.它隨着類的加載而加載,加載時機早
3.只執行一次,一般用來初始化操作
構造代碼塊:
1.定義在類中方法外,與構造方法平級
2.構造代碼塊優先於構造方法執行,每創建一次,構造代碼塊就會執行一次。
3.如果不寫構造代碼塊的話,程序中會有一個默認的無參構造代碼塊
4.若只寫了一個有參構造代碼塊,那麼就不會有默認的無參構造代碼塊了,此時如果想用無參構造的話必須自己寫一個無參構造方法
舉例
1.普通代碼塊
public class demo {
public static void main(String[] args) {
{
int x = 3;
System.out.println("普通代碼塊內的變量x=" + x);
}
int x = 1;
System.out.println("主方法內的變量x=" + x);
}
}
運行結果
普通代碼塊內的變量x=3
主方法內的變量x=1
2.構造代碼塊
class test{
public test(){
System.out.println("這是一個無參構造方法");
}
public test(int a){
System.out.println("這是一個有參構造方法,參數是a,a="+a);
}
}
public class demo {
public static void main(String[] args) {
new test();
new test(5);
}
}
輸出結果
這是一個無參構造方法
這是一個有參構造方法,參數是a,a=5
3.靜態代碼塊
class test{
public test(){
System.out.println("這是一個無參構造方法");
}
public test(int a){
System.out.println("這是一個有參構造方法,參數是a,a="+a);
}
static {
System.out.println("test的靜態代碼塊");
}
}
public class demo {
public static void main(String[] args) {
new test();
new test(5);
}
}
結果
test的靜態代碼塊
這是一個無參構造方法
這是一個有參構造方法,參數是a,a=5
例題:
看代碼寫出輸出結果
class Student {
static {
System.out.println("Student 靜態代碼塊");
}
{
System.out.println("Student 構造代碼塊");
}
public Student() {
System.out.println("Student 構造方法");
}
}
class StudentDemo {
static {
System.out.println("StudentDemo的靜態代碼塊");
}
public static void main(String[] args) {
System.out.println("我是main方法");
Student s1 = new Student();
Student s2 = new Student();
}
}
答案
StudentDemo的靜態代碼塊
我是main方法
Student 靜態代碼塊
Student 構造代碼塊
Student 構造方法
Student 構造代碼塊
Student 構造方法
1.靜態代碼塊先於主方法執行,創建Student對象時先執行Student中的靜態代碼塊,靜態代碼塊用static修飾,存在於方法區中,所以只在加載.class字節碼文件進入方法區時運行一次
2.new了Student對象之後,會先執行構造代碼塊進行初始化操作,然後執行構造方法,沒new一次就會執行一次這樣的操作,所以可以看到結果中構造代碼塊和構造方法都出現了兩次