类初始化顺序探究

1.本例子借用thinkingInJava第4版中文版P163中PolyConstructors.java例子修改后,说明一定问题:

该类中包含:静态属性、静态代码块、成员变量、普通代码块、父子类关系、子类重写父类方法

 

 

package com.iteye.bobby.base;

import static net.mindview.util.Print.*;

class Glyph {

	private static String baseStr = "static String field";
	
	static {
		System.out.println("baseStr = " + baseStr);
		System.out.println("Glyph.enclosing_method(static)");
	}
	
	{
		System.out.println("Glyph.enclosing_method(noraml)");
	}
	
	Glyph() {
		print("Glyph() before draw()");
		draw();
		print("Glyph() after draw()");
	}
	
	void draw() {
		print("Glyph.draw()");
	}
}

class RoundGlyph extends Glyph {
	private int radius = 1;
	private Glyph glyph = new Glyph();//成员变量赋值时创建对象

	static {
		System.out.println("RoundGlyph.enclosing_method(static)");
	}
	
	{
		System.out.println("RoundGlyph.enclosing_method(noraml)");
		System.out.println(" radius =  " + radius);
		System.out.println("new glyph() = " + glyph);
	}
	
	RoundGlyph(int r) {
		radius = r;
		print("RoundGlyph.RoundGlyph(), radius = " + radius);
	}

	void draw() {
		print("RoundGlyph.draw(), radius = " + radius);
	}
}

public class PolyConstructors {
	public static void main(String[] args) {
		new RoundGlyph(5);
	}
}





 

 

 

 

Result:

 

 

 

baseStr = static String field

Glyph.enclosing_method(static)

RoundGlyph.enclosing_method(static)

Glyph.enclosing_method(noraml)

Glyph() before draw()

RoundGlyph.draw(), radius = 0

Glyph() after draw()

Glyph.enclosing_method(noraml)

Glyph() before draw()

Glyph.draw()

Glyph() after draw()

RoundGlyph.enclosing_method(noraml)

 radius =  1

new glyph() = com.iteye.bobby.base.Glyph@61de33

RoundGlyph.RoundGlyph(), radius = 5

 

 

2.总结类的初始化顺序

1)类的初始化

a.初始化类属性、初始化类静态代码块(先父后子,按书写顺序执行)

2)对象的创建

a.所有的成员变量—包括该类,及它的父类中的成员变量--被分配内存空间,并赋予默认值。

b.为父类的成员变量赋值,并执行父类的普通代码块(按书写顺序执行)

c.执行父类构造函数

d.为子类的成员变量赋值,并执行子类普通的代码块(如果成员变量赋值时创建对象,则先父后子执行普通代码块和构造方法,然后在往下走)

e.执行子类构造函数

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值