物件導向---java代碼塊

來源:互聯網
上載者:User

標籤:執行個體   system   代碼塊   定義   而且   main   pre   運行   執行個體化   

概念:代碼塊是指用{}括起來的一段代碼。根據位置及聲明的關鍵字不同,代碼塊可分為普通代碼塊、構造塊、靜態代碼塊、同步代碼塊4種。1.普通代碼塊:

直接在方法中或在語句中定義

public class Test2 {    public static void main(String[] args) {        {                                    //定義普通代碼塊            int x = 30;                        //定義局部變數            System.out.println("普通代碼塊 x="+x);        }                int x = 100;                        //與局部變數名稱相同        System.out.println("代碼塊之外 x="+x);    }}

運行結果:

普通代碼塊 x=30
代碼塊之外 x=100

2.構造塊:

構造代碼塊是直接寫在類中的代碼塊。

public class Demo {    {                                    //定義構造塊        System.out.println("1、構造塊。");    }    public Demo(){                        //定義構造方法        System.out.println("2、構造方法");    }}public class Test2 {    public static void main(String[] args) {        new Demo();        new Demo();    }}

執行結果:

1、構造塊。
2、構造方法
1、構造塊。
2、構造方法

從輸出結果發現:構造塊優於構造方法執行,而且每次執行個體化對象時都會執行構造塊。

 

靜態代碼塊:

靜態代碼塊是使用static關鍵字聲明的代碼塊。

public class Demo {    {                                    //定義構造塊        System.out.println("1、構造塊。");    }    static{        System.out.println("0、靜態代碼塊");//定義靜態代碼塊    }    public Demo(){                        //定義構造方法        System.out.println("2、構造方法");    }}public class Test2 {    static{                                //在主方法所在的類中定義靜態代碼塊        System.out.println("在主方法所在的類中定義靜態代碼塊");    }    public static void main(String[] args) {        new Demo();                        //執行個體化對象        new Demo();                            }}

執行結果:

在主方法所在的類中定義靜態代碼塊
0、靜態代碼塊
1、構造塊。
2、構造方法
1、構造塊。
2、構造方法

從輸出結果發現:靜態代碼塊優於主方法執行,在類中定義的靜態代碼塊優於構造方法執行,而且不管產生多少個對象,靜態代碼塊只執行一次。

 

4.同步代碼塊:

在代碼塊上加上synchronized關鍵字,主要使用在多線程上,此代碼塊稱為同步代碼塊格式如下:

  synchronized(同步對象){

  需要同步的代碼;

  }

後續多線程再詳細練習。

物件導向---java代碼塊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.