1.static 使用場景:
- 修飾變量
- 修飾方法
- 可以修飾
- 靜態導包
法
?
import static java.lang.System.out**;
**import static *java.lang.Integer.;
**public class **StaticTest {
**public static void **main(String[] args) {
out.println(MAX_VALUE);
}
}
2 .static代碼塊執行順序 總結一下(父靜子靜,父非靜,父構造,子非靜,子構造)(同一類中相同內容的比如靜態或者非靜態實例的執行順序都是從上往下依次執行)
package net.csdn.se.statictest;
import net.csdn.se.statictest.Child;
public class Parent {
static {
System.out.println("父類的靜態塊");
}
private static String staticStr = getStaticStr();
private String str = getStr(); //非靜態變量成員變量
{
System.out.println("父類的實例塊"); //非靜態代碼塊
}
public Parent() {
System.out.println("父類的構造方法");
}
private static String getStaticStr() {
System.out.println("父類的靜態屬性初始化");
return null;
}
private String getStr() {
System.out.println("父類的實例屬性初始化");
return null;
}
public static void main(String[] args) {
new Child();
}
}
package net.csdn.se.statictest;
import java.util.HashMap;
public class Child extends Parent {
static {
System.out.println("子類的靜態塊"); //同一個類中,靜態內容的執行順序是由上往下執行的,非靜態也是一樣的
}
private static String staticStr = getStaticStr();
{
System.out.println("子類的實例塊");
}
public Child() {
System.out.println("子類的構造方法");
}
private String str = getStr();
private static String getStaticStr() {
System.out.println("子類的靜態屬性初始化");
return null;
}
private String getStr() {
System.out.println("子類的實例屬性初始化");
HashMap map = new HashMap();
map.put("key","value");
return null;
}
}
執行 new Child()的時候回先創建父類,上面代碼的執行結果順序是:
父類的靜態塊
父類的靜態屬性初始化
子類的靜態屬性初始化
子類的靜態塊
父類的實例屬性初始化
父類的實例塊
父類的構造方法
子類的實例塊
子類的實例屬性初始化
子類的構造方法
同一個類中的靜態內容的執行順序是代碼從上往下加載
結尾
看完如果對你有幫助,感謝點贊支持!