靜態(tài)方法,靜態(tài)成員變量,靜態(tài)代碼塊,實(shí)例代碼塊,構(gòu)造方法

  • 靜態(tài)方法,靜態(tài)成員變量,靜態(tài)代碼塊,
    對(duì)象公用的;

  • 靜態(tài)成員變量,靜態(tài)代碼塊;

按照代碼執(zhí)行順序,先定義靜態(tài)變量,才能引用靜態(tài)變量;
也就是先聲明再引用;


package staticpacakge;

public class StaticClass {

    static {
        System.out.println("static str print : ");
        System.out.println(staticStr+"\n");
    }

    //Error:(7, 28) java: 非法前向引用
    private static String staticStr = "haha";

}


  • 靜態(tài)方法
    調(diào)用的時(shí)候執(zhí)行;
  • 實(shí)例代碼塊,構(gòu)造方法
    對(duì)象私有的;

實(shí)例代碼塊先執(zhí)行,
再執(zhí)行構(gòu)造方法;

package staticpacakge;

public class StaticClass {

    private static String staticStr = "haha";

    {
        System.out.println("構(gòu)造代碼塊\n");
    }

    static {
        System.out.println("static str print : ");
        System.out.println(staticStr + "\n");
    }

    public StaticClass() {
        System.out.println("構(gòu)造方法\n");
    }


}


static str print : 
haha

構(gòu)造代碼塊

構(gòu)造方法

  • 靜態(tài)方法,靜態(tài)成員變量,靜態(tài)代碼塊,實(shí)例代碼塊,構(gòu)造方法
package staticpacakge;

public class StaticClass {

    private static String staticStr = "haha";

    {
        System.out.println("構(gòu)造代碼塊\n");
    }

    static {
        System.out.println("static str print : ");
        System.out.println(staticStr + "\n");
    }

    public StaticClass() {
        System.out.println("構(gòu)造方法\n");
    }


}


static str print : 
haha

構(gòu)造代碼塊

構(gòu)造方法

  • 靜態(tài)代碼塊僅執(zhí)行一次
package staticpacakge;

public class StaticMain {
    public static void main(String[] args) {

        new StaticClass();
        new StaticClass();
        new StaticClass();

    }
}


static str print : 
haha

構(gòu)造代碼塊

構(gòu)造方法

構(gòu)造代碼塊

構(gòu)造方法

構(gòu)造代碼塊

構(gòu)造方法

  • 總結(jié)

首次創(chuàng)建對(duì)象實(shí)例:
靜態(tài)代碼塊 - > 構(gòu)造代碼塊 -> 構(gòu)造方法;

非首次創(chuàng)建對(duì)象實(shí)例:
構(gòu)造代碼塊 -> 構(gòu)造方法;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容