問(wèn)題
如果在一個(gè)構(gòu)造器內(nèi)部,調(diào)用正在構(gòu)造的對(duì)象的某個(gè)動(dòng)態(tài)綁定方法,那會(huì)發(fā)生什么情況呢?
代碼
class Glyph {
void draw() {
print("Glyph.draw()");
}
/**
* 在基類的構(gòu)造器中,調(diào)用動(dòng)態(tài)綁定的方法(此方法被導(dǎo)出類覆蓋)
*
*/
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);
}
@Override
void draw() {
print("RoundGlyph.draw(), radius = " + radius);
}
}
class RectangularGlyph extends Glyph {
private int width = 4;
private int height = 5;
RectangularGlyph(int width, int height) {
this.width = width;
this.height = height;
print("RectangularGlyph.RectangularGlyph(), width = " + width + ", height = " + height);
}
void draw() {
print("RectangularGlyph.draw(), area = " + width *
height);
}
}
/**
* 在基類構(gòu)造器中,調(diào)用動(dòng)態(tài)綁定的方法,則導(dǎo)出類方法被調(diào)用時(shí),導(dǎo)出類的成員實(shí)際上還未被初始化;
* 當(dāng)調(diào)用到導(dǎo)出類的構(gòu)造器時(shí),導(dǎo)出類的成員已經(jīng)被初始化了;
*/
public class E15_PolyConstructors2 {
public static void main(String[] args) {
new RoundGlyph(5);
print("------------------------------");
new RectangularGlyph(2, 2);
}
}
輸出結(jié)果
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
------------------------------
Glyph() before draw()
RectangularGlyph.draw(), area = 0
Glyph() after draw()
RectangularGlyph.RectangularGlyph(), width = 2, height = 2
結(jié)論
類初始化的實(shí)際過(guò)程是:
- 在其他任何事物發(fā)生之前,將分配給對(duì)象的存儲(chǔ)空間初始化成二進(jìn)制的零。
這也解釋了為何基類構(gòu)造器中調(diào)用動(dòng)態(tài)綁定方法時(shí)為何radius = 0
、area = 0
- 調(diào)用基類構(gòu)造器
- 按照聲明的順序調(diào)用成員的初始化方法
- 調(diào)用導(dǎo)出類的構(gòu)造器主體
這解釋了導(dǎo)出類構(gòu)造器中為何:radius = 5
、width = 2, height = 2