- 动态绑定与前期绑定
- Static对象与Final对象不能覆盖,private 对象(方法的话,自动属于final)也不能进行覆盖。
- 复杂对象调用构造器要遵照下面的顺序
- 调用基类的构造器,这个过程会递归的调用下去。
- 按照声明顺序调用成员的初始化方法。
- 调用导出类构造器主体。
- 协变返回类型,导出类中被覆盖的方法可以返回基类方法的返回值类型的某种导出类型。
- 设计考虑时候优先考虑组合,而非继承
- 状态模式,动态的改变类型
//: polymorphism/Transmogrify.java
// Dynamically changing the behavior of an object
// via composition (the "State" design pattern).
import static net.mindview.util.Print.*;
class Actor {
public void act() {}
}
class HappyActor extends Actor {
public void act() { print("HappyActor"); }
}
class SadActor extends Actor {
public void act() { print("SadActor"); }
}
class Stage {
private Actor actor = new HappyActor();
public void change() { actor = new SadActor(); }
public void performPlay() { actor.act(); }
}
public class Transmogrify {
public static void main(String[] args) {
Stage stage = new Stage();
stage.performPlay();
stage.change();// 状态的改变
stage.performPlay();
}
} /* Output:
HappyActor
SadActor
*///:~
- 如果必须要执行清理,清理的顺序需要和声明顺序是相反的, 这样的话。
- 多态中潜藏的问题
//: polymorphism/PolyConstructors.java
// Constructors and polymorphism
// don't produce what you might expect.
import static net.mindview.util.Print.*;
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);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
} /* Output:
Glyph() before draw()
RoundGlyph.draw(), radius = 0
Glyph() after draw()
RoundGlyph.RoundGlyph(), radius = 5
*///:~