加载时:
1.先加载父类,再加载子类
2.按static 修饰的模块或属性的顺序进行加载
3.属性如果为类对象,则非空有值时才会初始化,加载属性对象所对应的类,并实例化
4.main方法(也是static)修饰的最后执行
实例化:
1.先实例化父类,再实例化子类
2.属性如果为对象,即没有使用static修饰时,则非空有值时才会初始化,加载属性对象所对应的类,并实例化
例子如下:
public class Test {
static Person person= new Person("Test");
static{
System.out.println("test static");
}
public Test() {
System.out.println("test constructor");
person=new Person("Test constructor");
}
public static void main(String[] args) {
System.out.println("============onload completed");
new MyClass();
}
}
class Person{
static{
System.out.println("person static");
}
public Person(String str) {
System.out.println("person "+str);
}
}
class MyClass extends Test {
Person person = new Person("MyClass");
static{
System.out.println("myclass static");
}
public MyClass() {
System.out.println("myclass constructor");
}
}
结果:
person static
person Test
test static
============onload completed
myclass static
test constructor
person Test constructor
person MyClass
myclass constructor