/*
* <p>
* 版权: ?2011
* </p>
*/
/**
* <p>
*
* </p>
*
* @see
* @author yangjun2
* @email yangjun1120@gmail.com
*
*/
public class Son extends Parent {
private final static String name = "gogogo";
static {
System.out.println("son init static");
}
public Son() {
System.out.println("son name:"+name+",this"+this);
}
public static void main(String[] args) throws Exception {
Son s = new Son();
System.out.println("ok!");
}
}
/*
* <p>
* 版权: ?2011
* </p>
*/
/**
* <p>
*
* </p>
*
* @see
* @author yangjun2
* @email yangjun1120@gmail.com
*
*/
public class Client {
private static Client c = new Client();
private Client() {
}
public static Client getInstance() {
return c;
}
public void test() {
Son s = new Son();
}
public static void main(String[] arg) throws Exception {
Client c = Client.getInstance();
c.test();
System.out.println("ok!");
}
}
/**
* <p>
*
* </p>
*
* @see
* @author yangjun2
* @email yangjun1120@gmail.com
*
*/
public class Parent {
static {
System.out.println("parent!");
Client c = Client.getInstance();
c.test();
// System.out.println(o);
}
}
执行结果:
parent!
son name:gogogo,thisSon@1fc2fb
son init static
son name:gogogo,thisSon@79717e
ok!
如果是一个单独的类Son,不集成Parent的话:
son init static
son name:gogogo,thisSon@79717e
ok!
但是继承后出现了意想 不到的结果。
说明一下:
1.主体Main函数,构造单例的Client c ,执行c.test(),即new Son() (第一个son实例)
2.根据类初始化原则,先初始化父类Parent,
3.因为Parent有static 代码,先执行static 代码
4.Parent static代码里面 获取单例的Client c执行c.test(),即new Son (第2个son实例)
5.因为Parent已经初始好,执行默认的构造函数
5.执行Son构造函数的剩余代码,System.out.println("son name:"+name+",this"+this),注意,此时Son static代码没有执行哦!
6.执行Son 的static 代码
7.因为Parent已经初始好,执行默认的构造函数
8.执行Son构造函数的剩余代码System.out.println("son name:"+name+",this"+this)
9.执行主体Main的剩余代码System.out.println("ok!");