`
hepeng19861212
  • 浏览: 146884 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

初始化

    博客分类:
  • java
 
阅读更多
//: c07:PolyConstructors.java
// Constructors and polymorphism
// don't produce what you might expect.
import com.bruceeckel.simpletest.*;

abstract class Glyph {
	abstract void draw();

	Glyph() {
		System.out.println("Glyph() before draw()");
		draw();
		System.out.println("Glyph() after draw()");
	}
}

class RoundGlyph extends Glyph {
	private int radius = 1;

	RoundGlyph(int r) {
		radius = r;
		System.out.println("RoundGlyph.RoundGlyph(), radius = " + radius);
	}

	void draw() {
		System.out.println("RoundGlyph.draw(), radius = " + radius);
	}
}

public class PolyConstructors {
	private static Test monitor = new Test();

	public static void main(String[] args) {
		new RoundGlyph(5);
		monitor.expect(new String[] {
				"Glyph() before draw()",
				"RoundGlyph.draw(), radius = 0", 
				"Glyph() after draw()",
				"RoundGlyph.RoundGlyph(), radius = 5" });	}
} // /:~

初始化的实际过程是:
1. 在其他任何事物发生之前,将分配给对象的存储空间初始化成二进制的零。
2. 如前所述的那样,调用基类构造器。此时,调用被重载的draw()方法(是的,是在调用RoundGlyph构造器之前调用的),由于步骤(1)的缘故,我们此时会发现radius的值为0。
3. 按照声明的顺序调用成员的初始化代码。
4. 调用导出类的构造器主体。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics