代码实例
public class MtTest1 {
public static void main(String[] args) {
System.out.println(MyChild1.str);
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent1 static block");
}
}
class MyChild1 extends MyParent1 {
static {
System.out.println("MyChild1 static blokc");
}
}
运行结果
MyParent1 static block
hello world
未执行子类的静态原因:对于静态字段来说,只有直接定义了该字段的类才会被初始化
另外一种情况
public class MtTest1 {
public static void main(String[] args) {
System.out.println(MyChild1.str2);
}
}
class MyParent1 {
public static String str = "hello world";
static {
System.out.println("MyParent1 static block");
}
}
class MyChild1 extends MyParent1 {
public static String str2 = "welcome";
static {
System.out.println("MyChild1 static blokc");
}
}
运行结果
MyParent1 static block
MyChild1 static blokc
welcome
原因:当一个类在初始化时,要求其父类全部都已经初始化完毕