代碼塊,java代碼塊
代碼塊分類:
1.普通代碼塊
2.構造代碼塊
3.靜態代碼塊
4.同步代碼塊
代碼塊不能獨立運行,須要依賴於其他配置,格式是:{ //代碼塊 }。
1.普通代碼塊
普通代碼塊,在方法名後(或方法體內)用一對"{}"括起來的資料區塊,並通過方法調用。
package cn.com.daimakuai;/** * PuTongDaiMaiKuai *@author:hushaoyu *2017-2-13上午9:27:02 *@描述:普通代碼塊 */public class PuTongDaiMaiKuai {public static void main(String[] args) {/**"{}"括起來的普通代碼塊;這裡的變數x=100作用範圍從"{"開始"}"結束,所以與下面的變數x=200互不影響, * 如果將下面的變數放在普通代碼前面將編譯錯誤,因為main的代碼區塊範圍比較大 */{int x = 100;System.out.println("普通代碼塊:"+x);}int x = 200;System.out.println("main方法:"+x);}/** * 結果輸出:普通代碼塊:100main方法:200 */} 2.構造代碼塊構造代碼塊:在類中直接定義的,沒有任何首碼、尾碼以及修飾符的代碼塊。
構造代碼塊和構造方法一樣都是在對象產生時被調用,但調用時機比構造方法早,所以構造代碼塊可以用來初始化成員變數。如果一個類中有多個構造方法,這些構造方法都需要初始化成員變數,那麼可以把每個構造方法中相同的代碼部分抽取出來,集中一起放在構造代碼塊中,利用構造代碼塊來初始化共有的成員變數,減少重複代碼。
package cn.com.daimakuai;/** * ConstroctDaimakuai * @author:hushaoyu * @2017-2-13上午10:02:55 * @描述:構造代碼塊 */public class ConstroctDaimakuai {public static void main(String[] args) {Person p1 = new Person();System.out.println("*******************");Person p2 = new Person("hushaoyu");}}// Person類class Person {private int x;private String name;// 構造代碼塊{System.out.println("構造代碼塊執行-------");// 對類的成員變數x進行初始化,如果不放置在代碼塊中,要達到同樣效果,需要分別出現在2個構造方法中。x = 100;}// 無參構造方法Person() {System.out.println("構造方法執行-------");name = "huyuyu";show();}// 有參構造方法Person(String name) {System.out.println("構造方法執行-------");this.name = name;show();}/** * show方法 */private void show() {System.out.println("welcome!" + name);System.out.println("x=" + x);}/**結果輸出:構造代碼塊執行-------構造方法執行-------welcome!huyuyux=100*******************構造代碼塊執行-------構造方法執行-------welcome!hushaoyux=100*/}3.靜態代碼塊
靜態代碼塊:static修飾並用"{}括起來的代碼塊。
特點:用來初始化靜態成員變數,最先執行(隨著類的載入而載入),只執行一次。
package cn.com.daimakuai;/** * Staticdaimakuai *@author:hushaoyu *2017-2-13上午10:45:49 *@描述:靜態代碼塊 */public class Staticdaimakuai {public static void main(String[] args) {System.out.println("main方法執行-------");System.out.println("***建立第1個對象***");new Staticdaimakuai();System.out.println("***建立第2個對象***");new Staticdaimakuai();System.out.println("***建立第3個對象***");new Staticdaimakuai();}//靜態代碼塊static{System.out.println("靜態代碼塊執行-------");}//構造方法Staticdaimakuai(){System.out.println("構造方法執行------");}//構造代碼塊{System.out.println("構造代碼塊執行------");}/** 結果輸出: 靜態代碼塊執行------- main方法執行------- ***建立第1個對象*** 構造代碼塊執行------ 構造方法執行------ ***建立第2個對象*** 構造代碼塊執行------ 構造方法執行------ ***建立第3個對象*** 構造代碼塊執行------ 構造方法執行------*/ }4.同步代碼塊同步代碼塊:運用在多線程方面。