Java程序运行时,会首先运行到某类的main()方法,随即开始加载该类,同时对static成员初始化。若该类具有超类,则从根基类开始加载类并初始化类的static成员,因为有时候子类的成员初始化会依赖于基类的初始化成员。错误的理解是:Java运行到程序中,若遇到对类的操作(比如生成类对象)时才加载对应于操作的类并初始化其static成员。
//StaticInitialSequence.java
//The class including main method is loaded while the application goes to the main().
package com.msn.spaces.bryantd001;
class SuperClass{
private static StringBuffer strBufSuper;
static{
strBufSuper=new StringBuffer("strBufSuper is a StringBuffer in the super class.");
System.out.println(strBufSuper);
}
}
public class StaticInitialSequence extends SuperClass{
private static String strSub=new String("strSub is a String in the sub class.");
static{
System.out.println(strSub);
}
public static void main(String[] args){
AnotherClass acObj=new AnotherClass();
StaticInitialSequence sisObj=new StaticInitialSequence();
System.out.println();
System.out.println("The result I expected in the past are:");
System.out.println("i=100 is a Integer in another class.");
System.out.println("strBufSuper is a StringBuffer in the super class.");
System.out.println("strSub is a String in the sub class.");
}
}
class AnotherClass{
private static int i;
static{
i=100;
System.out.println("i= "+i+" is a Integer in another class.");
}
}