第七章: Polymorphism
1、 Upcasting revisited--Taking an object reference and treating it as a reference to its base type.(通过绑定来实现多态的方法调用)
Method-call binding方法调用的绑定,分前绑定和后绑定--early binding(When binding is performed before the program is run)、Late binding also called dynamic binding or run-time binding(means that the binding occurs at run time, based on the type of object)
定义抽象类:abstract class Instrument {private int i; // Storage allocated for each
public abstract void play(Note n);
public String what() {
return "Instrument";
}
public abstract void adjust();
}
2、Constructors and polymorphism
2.1)The base-class constructor is called. This step is repeated recursively such that the root of the hierarchy is constructed first, followed by the next-derived class, etc., until the most-derived class is reached.
2.2)Member initializers are called in the order of declaration.
2.3)The body of the derived-class constructor is called
a good guideline for constructors is, “Do as little as possible to set the object into a good state, and if you can possibly avoid it, don’t call any methods.” The only safe methods to call inside a constructor are those that are final in the base class. (This also applies to private methods, which are automatically final.)理解如下示例:
import com.bruceeckel.simpletest.*;
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw(); //call a dynamically-bound method(多态性:所有的东西都是继承下来的)
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() { //基类构造函数在调用的时侯,radius还没有初始化
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"
});
}
} ///:~