例一:
package test_load;
public class Animal {
public String test = "AnimalField";
public static String testStatic = "AnimalStaticField";
public Animal(){
System.out.println("Animal中默认无参数的构造方法");
}
{
this.test();
System.out.println("Animal的普通程序块"+test);
}
static {
Animal.testStatic();
System.out.println("Animal的静态程序块"+testStatic);
}
public void test(){
System.out.println("我是Animal中的普通方法");
}
public static void testStatic() {
System.out.println("我是Animal中的静态方法");
}
}
package test_load;
public class Person extends Animal{
public String test = "AnimalField";
public static String testStatic = "AnimalStaticField";
public Person(){
//隐藏代码super();
System.out.println("Person中无参数的构造方法");
}
{
this.testPerson();
System.out.println("Person的普通程序块"+test);
}
static {
Person.testStatic();
System.out.println("Person的静态程序块"+testStatic);
}
public void testPerson(){
System.out.println("我是Person中的普通方法");
}
public static void testStatic() {
System.out.println("我是Person中的静态方法");
}
}
package test_load;
public class RunMain {
public static void main(String[] args){
//加载类的过程 静态元素已经加载了
//1.加载父类
//2.父类产生自己的静态空间 加载静态空间时的顺序 加载属性 加载方法 加载块
// 执行静态块
//3.加载子类
//4.子类产生自己的静态空间 加载属性 加载方法 加载块
// 执行静态块
//5.开辟对象空间
//6.加载父类中的非静态成员 属性 方法 块 构造方法
//7. 执行块 执行构造方法
//8.加载子类中的非静态成员 属性 方法 块 构造方法
//9. 执行块 执行构造方法
//10.将对象空间的地址引用交给变量存储
Person p = new Person();
}
}
例二:
public class Person {
//public Person p = new Person();
//这里如果添加这行代码 会出现错误 栈内存溢出错误StackOverflowError
public static Person p1 = new Person();
//静态初始化只执行一次
//先输出普通程序块的内容
//再输出构造方法
//然后再执行静态块
public String test = "AnimalField";
public static String testStatic = "AnimalStaticField";
public Person(){
System.out.println("Person中无参数的构造方法");
}
{
System.out.println("Person的普通程序块"+test);
}
static {
System.out.println("Person的静态程序块"+testStatic);
}
public void testPerson(){
System.out.println("我是Person中的普通方法");
}
public static void testStatic() {
System.out.println("我是Person中的静态方法");
}
public static void main(String[] args){
Person p1 = new Person();
Person p2 = new Person();//静态初始化与静态块只会执行一次
}
}
执行结果:
Person的普通程序块AnimalField
Person中无参数的构造方法
Person的静态程序块AnimalStaticField
Person的普通程序块AnimalField
Person中无参数的构造方法
Person的普通程序块AnimalField
Person中无参数的构造方法