next up previous
Next: 8.6 ダウンキャスト Up: 8 要素型と参照型 Previous: 8.4 型変換

8.5 アップキャスト

サブクラスには親クラス中のメンバーはすべて含まれるため 継承関係を上にたどる型変換であるアップキャストは安全に 行われる.

//: Wind.java
// Copyright (c) Bruce Eckel, 1998
// Inheritance & upcasting
import java.util.*;

class Instrument {
  public void play() {}
  static void tune(Instrument i) {
    // ...
    i.play();
  }
}

// Wind objects are instruments
// because they have the same interface:
class Wind extends Instrument {
  public static void main(String[] args) {
    Wind flute = new Wind();
    Instrument.tune(flute); // Upcasting
  }
}


generated through LaTeX2HTML. M.Inaba 平成18年5月7日