public class Father {
public static String desc = "Father";
static {
System.out.println(desc);
}
Father(){
System.out.println("Father Constructor");
}
String str = fun();
public String fun(){
System.out.println("Father not static");
return "Father not static";
}
}
public class Child extends Father{
public static String desc = "Child";
static {
System.out.println(desc);
}
Child(){
System.out.println("Child Constructor");
}
String str = fun();
public String fun(){
System.out.println("Child not static");
return "Child not static";
}
public static void main(String[] args) {
Child c = new Child();
}
}
請問輸出是什麼,為什麼,
我測試的輸出:
Father
Child
Child not static
Father Constructor
Child not static
Child Constructor
關於Father static為什麼不出來我不懂,求幫助
初始化順序為:
類初始化:按出現順序初始化靜態類成員、static塊
類實例初始化:按出現順序初始化實例成員初始化和按規則調用構造方法
父類實例初始化過程中,由於實例化的是子類Child,父類的str對象在初始化過程中調用的fun()實際上是子類的重寫方法,而並非父類聲明的fun(),如果把父類的fun和子類的fun改為不同的簡單名稱,比如父類改為fun2(),那麼就會輸出Father not static而非Child not static