方法調用綁定
將一個方法調用和一個方法主體關聯起來稱作綁定。
若綁定發生在程序運行前(如果有的話,由編譯器和鏈接器實現),叫做前期綁定。前期綁定是面向過程語言默認的綁定方式,例如 C 語言中,就只有前期綁定這一種方法調用。
在運行時根據對象類型進行綁定,叫做後期綁定,也稱爲動態綁定或運行時綁定。也就是說編譯器不知道對象的類型,但是方法調用機制能找到正確的方法體並調用。每種語言的後期綁定機制不同,但是可以想到,對象中一定存在某種類型信息。
Java 中除了 static 和 final 方法(private 方法也是隱式的 final)外,其他所有方法都是後期綁定。
構造器內部多態方法的行爲
class Glyph {
void draw() {
System.out.println("Glyph.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);
}
@Override
void draw() {
System.out.println("RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
// 運行結果:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
在基類的構造器中,能安全調用的只有基類的 final 方法(也適用於被看作 final 的 private 方法)。