第七章: Polymorphism

第七章: 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"

    });

  }

} ///:~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值