【迁移】Think In Java 多态学习

    1. 动态绑定与前期绑定
    2. Static对象与Final对象不能覆盖,private 对象(方法的话,自动属于final)也不能进行覆盖。
    3. 复杂对象调用构造器要遵照下面的顺序
      1. 调用基类的构造器,这个过程会递归的调用下去。
      2. 按照声明顺序调用成员的初始化方法。
      3. 调用导出类构造器主体。
    4. 协变返回类型,导出类中被覆盖的方法可以返回基类方法的返回值类型的某种导出类型。
    5. 设计考虑时候优先考虑组合,而非继承
    6. 状态模式,动态的改变类型

//: polymorphism/Transmogrify.java
// Dynamically changing the behavior of an object
// via composition (the "State" design pattern).
import static net.mindview.util.Print.*;</p>

<p>class Actor {
  public void act() {}
}</p>

<p>class HappyActor extends Actor {
  public void act() { print(&quot;HappyActor&quot;); }
}</p>

<p>class SadActor extends Actor {
  public void act() { print(&quot;SadActor&quot;); }
}</p>

<p>class Stage {
  private Actor actor = new HappyActor();
  public void change() { actor = new SadActor(); }
  public void performPlay() { actor.act(); }
}</p>

<p>public class Transmogrify {
  public static void main(String[] args) {
    Stage stage = new Stage();
    stage.performPlay();
    stage.change();// 状态的改变
    stage.performPlay();
  }
} /* Output:
HappyActor
SadActor
*/

    1. 如果必须要执行清理,清理的顺序需要和声明顺序是相反的, 这样的话。
    2. 多态中潜藏的问题

//: polymorphism/PolyConstructors.java
// Constructors and polymorphism
// don't produce what you might expect.
import static net.mindview.util.Print.*;</p>

<p>class Glyph {
  void draw() { print(&quot;Glyph.draw()&quot;); }
  Glyph() {
    print(&quot;Glyph() before draw()&quot;);
    draw();// 执行这个方法时候,调用的其实是被覆盖以后的方法
    print(&quot;Glyph() after draw()&quot;);
  }
}</p>

<p>class RoundGlyph extends Glyph {
  private int radius = 1;//执行这一步以前, 会先执行父类的构造器, 然后父类的构造器又会直接调用覆盖以后的方法
  RoundGlyph(int r) {
    radius = r;
    print(&quot;RoundGlyph.RoundGlyph(), radius = &quot; + radius);
  }
  void draw() {
    print(&quot;RoundGlyph.draw(), radius = &quot; + radius);
  }
}</p>

<p>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
*/

发表评论

邮箱地址不会被公开。 必填项已用*标注