您的位置:首页 > 编程语言 > Java开发

java中带继承类的加载顺序详解及实战

2016-05-12 23:14 591 查看
一、背景:

  在面试中,在java基础方面,类的加载顺序经常被问及,很多时候我们是搞不清楚到底类的加载顺序是怎么样的,那么今天我们就来看看带有继承的类的加载顺序到底是怎么一回事?在此记下也方便以后复习巩固!

二、测试步骤:

1.父类代码

package com.hafiz.zhang;

public class Fu
{
private int i = print("this is father common variable");
private static int j = print("this is father static variable");
static{
System.out.println("this is father static code block");
}
{
System.out.println("this is father common code block");
}
public Fu(){
System.out.println("this is father constructor");
}

static int print(String str){
System.out.println(str);
return 2;
}
}


2.子类代码

package com.hafiz.zhang;

public class Zi extends Fu
{
private int l = print("this is son common variable");
private static int m = print("this is son stati variable");
static{
System.out.println("this is son static code block");
}
{
System.out.println("this is son common code block");
}
public Zi(){
System.out.println("this is son constructor");
}
public static void main(String[] args) {
new Zi();
}
}


最后运行结果为:



下面让我们修改一下两个类中静态代码块和静态成员变量的位置并重新运行

3.修改后的父类代码

package com.hafiz.zhang;

public class Fu
{
static{
System.out.println("this is father static code block");
}
{
System.out.println("this is father common code block");
}
public Fu(){
System.out.println("this is father constructor");
}

static int print(String str){
System.out.println(str);
return 2;
}
private int i = print("this is father common variable");
private static int j = print("this is father static variable");
}


4.修改后的子类代码

package com.hafiz.zhang;

public class Zi extends Fu
{
static{
System.out.println("this is son static code block");
}
{
System.out.println("this is son common code block");
}
public Zi(){
System.out.println("this is son constructor");
}
public static void main(String[] args) {
new Zi();
}
private int l = print("this is son common variable");
private static int m = print("this is son stati variable");
}


修改后的运行结果:



三、测试结果

由测试结果可知:程序首先加载类,然后再对类进行初始化。

加载类的顺序为:先加载基类,基类加载完毕后再加载子类。

初始化的顺序为:先初始化基类,基类初始化完毕后再初始化子类。

最后得出类加载顺序为:先按照声明顺序初始化基类静态变量和静态代码块,接着按照声明顺序初始化子类静态变量和静态代码块,而后按照声明顺序初始化基类普通变量和普通代码块,然后执行基类构造函数,接着按照声明顺序初始化子类普通变量和普通代码块,最后执行子类构造函数。

对于本测试中的执行顺序为:先初始化static的变量,在执行main()方法之前就需要进行加载。再执行main方法,如果new一个对象,则先对这个对象类的基本成员变量进行初始化(非方法),包括构造代码块,这两种是按照编写顺序按序执行的,再调用构造函数。 关于继承的初始化机制,首先执行含有main方法的类,观察到Zi类含有基类Fu,即先加载Fu类的static变量,再加载Zi类的static变量。加载完static变量之后,调用main()方法,new Zi()则先初始化基类的基本变量和构造代码块,再调用基类的构造方法。然后再初始化子类Zi的基本变量和构造代码块,再执行子类的构造函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: