靜態(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)造方法;