Next: , Previous: , Up: The objects.fs model   [Contents][Index]


6.24.3.2 Basic objects.fs Usage

以下のようにして graphical オブジェクト(図形オブジェクト)のクラスを定義できます:

object class \ クラス名 "object" は親クラスです
  selector draw ( x y graphical -- )
end-class graphical

このコードは、 draw 操作を持つクラス graphical を定義します。 任意の graphical オブジェクトに対して draw 操作を実行できます。例:

100 100 t-rex draw

ここで、 t-rex は、 graphical オブジェクトを生成するワード(定数(constant)など)です。

graphical オブジェクトを作成するにはどうすればよいでしょうか? 現在の定義では、 有用な graphical オブジェクトを作成できません。 クラス graphical は graphical オブジェクト一般を記述しますが、 具体的な graphical オブジェクト・タイプを記述しません(C++ ユーザーはこれを「抽象クラス」(abstract class)と呼びます)。 たとえば、 クラス graphical にはセレクター draw のメソッドがありません。

具体的な graphical オブジェクトのために、 クラス graphical の子クラスを定義します。 例:

graphical class \ 親クラスは graphical
  cell% field circle-radius

:noname ( x y circle -- )
  circle-radius @ draw-circle ;
overrides draw

:noname ( n-radius circle -- )
  circle-radius ! ;
overrides construct

end-class circle

ここでは、 フィールド circle-radius を持つクラス circlegraphical の子として定義しています(フィールド circle-radius は構造体のフィールドと同じように動作します(see Structures)。 セレクター drawconstruct 用の新しいメソッドを定義します(constructgraphical の親クラスの object クラスで定義されています))。

以下のようにして、 ヒープ上(つまり、 allocate されたメモリ)に circle を作成できます:

50 circle heap-new constant my-circle

heap-newconstruct を呼び出し、 フィールド circle-radius を 50 で初期化します。 以下のようにして、 この新しい円を (100,100) の位置に描画(draw)できます:

100 100 my-circle draw

注意: セレクターを呼び出すことができるのは、 TOS 上のオブジェクト(受信オブジェクト) が、 セレクターが定義されたクラス、 またはその子孫の 1 つに属している場合のみです。 たとえば、 draw は、 graphical またはその子孫(例: circle)に属するオブジェクトに対してのみ呼び出すことができます。 end-class の直前の検索順序スタック(the search order)は、 class の直後と同じである必要があります。