例子代码摘抄自《 [Bruce.Eckel编程思想系列丛书].Thinking.In.Java.Third.Edition.CHS.pdf》
项目环境:windows/eclips/jdk 1.7
新建一个java project命名为test,项目目录如下
Insect.java代码如下
package com.test2;
public class Insect {
private int i = 9;
protected int j;
Insect(){
System.out.println("i = " + i + ", j = " + j);
j=39;
}
private static int x1 = print("static Insect.x1 initialized");
static int print(String s){
System.out.println(s);
return 47;
}
}
Beetle.java继承Insect.java,代码如下
package com.test;
public class Beetle extends Insect {
private int k = print("Beetle.k initialized");
public Beetle(){
System.out.println("k = " + k);
System.out.println("j = " + j);
}
private static int x2 = print("static Beetle.x2 initialized");
public static void main(String[] args){
System.out.println("Beetle constructor");
Beetle b = new Beetle();
}
}
执行Beetle.java的main方法,得到结果如下
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
i = 9, j = 0
Beetle.k initialized
k = 47
j = 39
结果分析:
在运行Beetle类的main()方法时,类加载器会对Beetle进行初始化,而在此之前,会对其基类(Insect类)先初始化,如果还存在基类的基类,以此类推初始化;所以在此
工程项目中先初始化的是Insect类,后初始化Beetle类,依次执行类中的初始化语句,如static变量和static块,并对变量设置默认值,整型的默认值为0;
先执行Insect类中的
private static int x1 = print(“static Insect.x1 initialized”);
打印出:static Insect.x1 initialized
然后执行子类Beetle类的
private static int x2 = print(“static Beetle.x2 initialized”);
打印出:static Beetle.x2 initialized
初始化完成,执行main()方法中的代码:
System.out.println(“Beetle constructor”);
打印出:
Beetle constructor
如果没有接下来的实例化语句:输出结果就会是:
static Insect.x1 initialized
static Beetle.x2 initialized
Beetle constructor
对Beetle类的实例化,调用子类无参构造方法,会先去调用其基类的无参构造方法(如未用super关键字调用,且调用有参构造函数默认调用,需手动调用),如果还存在基类
的基类,以此类推调用;
所以先调用了父类的无参构造函数Insect()
打印出:
i = 9, j = 0(i初始化赋值为9,j默认赋值0)
然后执行子类的构造方法Beetle()
打印出:
k = 47
j = 39
(k由子类初始化为47,j在调用父类构造方法时,赋值为39)
下面是我学习过程,参考的博客文章地址:
http://blog.csdn.net/moreevan/article/details/6968718
http://blog.csdn.net/gjanyanlig/article/details/6818655
我只是一个新手,记录一下自己学习过程的一些理解,如果有什么错误的地方,望大佬指教