08-02 Java 代碼塊,代碼塊執行的先後順序問題

來源:互聯網
上載者:User

標籤:多個   順序   pre   方法   面試   out   code   stat   不同   

代碼塊

/*    代碼塊:在Java中,使用{}括起來的代碼被稱為代碼塊。    根據其位置和聲明的不同,可以分為        局部代碼塊:局部位置,用於限定變數的生命週期。        構造代碼塊:在類中的成員位置,用{}括起來的代碼。每次調用構造方法執行前,都會先執行構造代碼塊。            作用:可以把多個構造方法中的共同代碼放到一起,對對象進行初始化。        靜態代碼塊:在類中的成員位置,用{}括起來的代碼,只不過它用static修飾了。            作用:一般是對類進行初始化。                面試題?        靜態代碼塊,構造代碼塊,構造方法的執行順序?        靜態代碼塊 -- 構造代碼塊 -- 構造方法        靜態代碼塊:只執行一次        構造代碼塊:每次調用構造方法都執行*/class Code {    static {        int a = 1000;        System.out.println(a);    }    //構造代碼塊    {        int x = 100;        System.out.println(x);    }        //構造方法    public Code(){        System.out.println("code");    }        //構造方法    public Code(int a){        System.out.println("code");    }        //構造代碼塊    {        int y = 200;        System.out.println(y);    }        //靜態代碼塊    static {        int b = 2000;        System.out.println(b);    }}class CodeDemo {    public static void main(String[] args) {        //局部代碼塊        {            int x = 10;            System.out.println(x);        }        //找不到符號        //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();        System.out.println("---------------");        Code c3 = new Code(1);    }}

看程式,寫結果:

/*    寫程式的執行結果。    分析過程:    載入class時,先執行A,    main主方法,執行B,    new student()第一次前,載入student class,執行C,    new student()第一次時,執行E,再執行D。因為構造方法放在構造代碼塊前,也會先執行構造代碼塊    new student()第二次前,不再執行C,因為靜態代碼塊只執行一次    new student()第二次時,執行E,再執行D。        執行順序:    林青霞都60了,我很傷心    我是main方法  ---     Student 靜態代碼塊    Student 構造代碼塊    Student 構造方法        Student 構造代碼塊    Student 構造方法*/class Student {    //C    static {        System.out.println("Student 靜態代碼塊");    }        //D    public Student() {        System.out.println("Student 構造方法");    }        //E    {        System.out.println("Student 構造代碼塊");    }        }class StudentDemo {    static {        //A        System.out.println("林青霞都60了,我很傷心");    }        public static void main(String[] args) {        //B        System.out.println("我是main方法");                Student s1 = new Student();        Student s2 = new Student();    }}

 

08-02 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.