JAVA語言基礎-面向對象(代碼塊)

  • 代碼塊概述
    • 在Java中,使用{}括起來的代碼被稱爲代碼塊。
  • 代碼塊分類
    • 根據其位置和聲明的不一樣,能夠分爲局部代碼塊,構造代碼塊,靜態代碼塊,同步代碼塊(多線程講解)。
  • 常見代碼塊的應用
    • a:局部代碼塊
      • 在方法中出現;限定變量生命週期,及早釋放,提升內存利用率
    • b:構造代碼塊 (初始化塊)
      • 在類中方法外出現;多個構造方法方法中相同的代碼存放到一塊兒,每次調用構造都執行,而且在構造方法前執行
    • c:靜態代碼塊
      • 在類中方法外出現,並加上static修飾;用於給類進行初始化,在加載的時候就執行,而且只執行一次。
      • 通常用於加載驅動
class Demo1_Code {
	public static void main(String[] args) {
		{
			int x = 10;						//局部代碼塊:限定變量的聲明週期
			System.out.println(x);
		}
		
		Student s1 = new Student();
		System.out.println("---------------");
		Student s2 = new Student("張三",23);
	
	}

	static {
		System.out.println("我是在主方法類中的靜態代碼塊");
	}
}

class Student {
	private String name;
	private int age;

	public Student(){
		//study();
		System.out.println("空參構造");
	}					//空參構造

	public Student(String name,int age) {//有參構造
		//study();
		this.name = name;
		this.age = age;
		System.out.println("有參構造");
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return age;
	}

	{											//構造代碼塊:每建立一次對象就會執行一次,優先於構造函數執行
		//System.out.println("構造代碼塊");
		study();
	}

	public void study() {
		System.out.println("學生學習");
	}

	static {									//隨着類加載而加載,且只執行一次
		System.out.println("我是靜態代碼塊");	//做用:用來給類進行初始化,通常用來加載驅動
	}											//靜態代碼塊是優先於主方法執行
}
class Student {
	static {
		System.out.println("Student 靜態代碼塊");
	}
	
	{
		System.out.println("Student 構造代碼塊");
	}
	
	public Student() {
		System.out.println("Student 構造方法");
	}
}

class Demo2_Student {
	static {
		System.out.println("Demo2_Student靜態代碼塊");
	}
	
	public static void main(String[] args) {
		System.out.println("我是main方法");
		
		Student s1 = new Student();
		Student s2 = new Student();
	}
}
相關文章
相關標籤/搜索