`
Copperfield
  • 浏览: 254898 次
  • 性别: Icon_minigender_1
  • 来自: 上海
博客专栏
C407adc3-512e-3a03-a056-ce4607c3a3c0
java并发编程陷阱
浏览量:24657
社区版块
存档分类

thinking in java-构造器内部的多态行为

 
阅读更多
class Glyph {
	void draw() { print("Glyph.draw()"); }
	Glyph() {
		print("Glyph() before draw()");
		draw();
		print("Glyph() after draw()"); 
	}
}

class RoundGlyph extends Glyph {
	private int radius = 1;
	RoundGlyph(int r) {
		radius = r;
		print("RoundGlyph.RoundGlyph(), radius = " + radius);
	}
	void draw() {
		print("RoundGlyph.draw(), radius = " + radius);
	}
}

class RectangularGlyph extends Glyph {
	private int length = 2;
	private int width = 4;
	RectangularGlyph(int l, int w) {
		length = l;
		width = w;
		print("RectangularGlyph.RectangularGlyph(), length = " 
			+ length + ", width = " + width);
	}
	void draw() {
		print("RectangularGlyph.draw(), length = " + length 
			+ ", width = " + width);
	}
}


public class PolyConstructors15 {
	public static void main(String[] args) {
		new RoundGlyph(5);
		new RectangularGlyph(3, 6);
	}
}

 output:

Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
Glyph() before draw()
RectangularGlyph.draw(), length = 0, width = 0
Glyph() after draw()
RectangularGlyph.RectangularGlyph(), length = 3, width = 6

 

注意初始化顺序:

1、在任何事情发生之前,将分配给对象的存储空间初始化成二进制的0。

2、调用父类构造器,调用被子类覆盖的方法,由于子类构造器尚未执行,此时子类中的radius仍然是0.

3、按照声明的顺序调用成员的初始化方法。

4、调用子类的构造器。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics