/*
在加载类时,Java虚拟机先加载父类再加载子类,再对静态初始化块、
静态成员变量(类变量)、静态方法进行一次初始化。
只有调用new方法时才会创建类的对象。按照父子继承关系进行初始化,
首先执行父类的初始化块部分,然后是父类的构造方法,再执行子类的
初始化块,最后是子类的构造方法。
销毁对象的过程是:首先销毁子类部分,再销毁父类部分。
*/
public class InheritanceLoadOrder
{
public static void main(String[] args)
{
System.out.println("不创建对象直接访问静态方法时的输出:");
Child.childMethod();
System.out.println("\n\t>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n");
System.out.println("通过new创建对象,访问非静态方法时的输出:");
new Child("").display();
System.gc();//通知虚拟机进行垃圾回收
}
}
class Parent
{
private int x = 15;
private static int y = getValue(20);
{
System.out.println("执行Parent的初始化代码块");
int x = 70;
int y = getValue(30);
}
static
{
System.out.println("执行Parent的静态初始化代码块");
int sx = 70;
int sy = getValue(30);
}
public Parent()
{
System.out.println("Parent默认构造函数被调用");
}
public void display()
{
System.out.println("Parent的display方法被调用");
System.out.println("x = " + this.x + " ; y = " + y);
parentMethod();
}
public static void parentMethod()
{
System.out.println("Parent的parentMethod方法被调用");
}
public static int getValue(int num)
{
System.out.println("Parent的getValue(int num)方法被调用");
return ++num;
}
//当Java在进行垃圾回收时,会自动地调用对象的finalize()方法
protected void finalize()
{
System.out.println("Parent对象被垃圾收回器收回");
}
}
class Child extends Parent
{
{
System.out.println("执行Child的初始化代码块");
int z = 30;
}
static
{
System.out.println("执行Child的静态初始化代码块");
}
public Child()
{
super();
System.out.println("Child的构造方法被调用");
}
public Child(String str)
{
System.out.println("Child带参的构造方法被调用");
}
public static void childMethod()
{
System.out.println("Child的childMethod方法被调用");
}
//当Java在进行垃圾回收时,会自动地调用对象的finalize()方法
protected void finalize()
{
System.out.println("Child对象被垃圾收回器收回");
}
}
/*
只有在创建一个对象时,才会按先父类后子类的顺序初始化类的初始化块、
构造方法等。如果只访问类的静态方法,Java虚拟机不会初始化这些代码。
对于每个类,Java虚拟机只加载一次,在加载时,初始化类的静态方法、
静态变量以及静态初始化块。System类的gc()方法用于通知Java虚拟机
进行垃圾回收,但不保证会立即执行,至于何时进行垃圾回收,完全由
虚拟机决定。在进行垃圾回收时,虚拟机会调用对象的finalize()方法。
*/
运行结果: