代碼塊,看程序寫結果--學習筆記--18

代碼塊:在Java中,使用{}括起來的代碼稱爲代碼塊
根據其位置和聲明的不同,可以分爲
(1)局部代碼塊:局部位置,用於限定變量的生命週期
(2)構造代碼塊:在類中的成員位置,用{}括起來的代碼,每次調用構造方法執行前,都會先執行構造代碼塊。
作用:可以把多個構造方法中的共同代碼放到一起,對對象進行初始化
(3)靜態代碼塊:在類中的成員位置,用()括起來的代碼,只不過它用static修飾了
作用:一般是對類初始化
面試題:靜態代碼塊,構造代碼塊,構造方法的執行順序?
靜態代碼塊—構造代碼塊—構造方法
靜態代碼塊:只執行一次
構造代碼塊:每次調用方法都執行

class Code{
	//構造代碼塊
	
	static {
		int a=1000;
		System.out.println(a);
	}
	//構造方法
	public Code() {	
		System.out.println("code");
	}
	//構造代碼塊
	{
		int y=200;
		System.out.println(y);
	}
	//靜態代碼塊
	static {
		int b=2000;
		System.out.println(b);
	}
}
public class Test {
	public static void main(String[] args) {
		//局部代碼塊
		{
			int x=10;
			System.out.println(x);	
		}	
		
		{
			int y=20;
			System.out.println(y);
		}
		System.out.println("------------");
		Code c=new Code();
		System.out.println("------------");
		Code c2=new Code();
	}				
}

在這裏插入圖片描述
先執行主方法的static代碼塊,因爲main方法纔會用到學生,虛擬機調用main方法。
即就是在同一個方法中,靜態方法優先於main方法執行,因爲main方法要去調方法。main方法加載完後,纔去調用Student類,先執行靜態方法,靜態方法只執行一次。

class Student{
	static {
		System.out.println("student 靜態代碼塊");
	}
	{
		System.out.println("student 構造代碼塊");
	}
	public Student() {
		System.out.println("student 構造方法");
	}
}	
	
class StudentDemo {
	static {
		System.out.println("易烊千璽");
	}
public static void main(String args[]) {
	System.out.println("main 方法");
	Student s1=new Student();
	Student s2=new Student();

}
}

在這裏插入圖片描述

發佈了24 篇原創文章 · 獲贊 4 · 訪問量 1745
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章